如何解决 React Native 中的错误 'cb is not a function'?

How to solve an error 'cb is not a function' in React Native?

当前代码

Index.js

import Auth from 'app/src/common/Auth';

export default class Index extends React.Component {

async componentDidMount() {
    this.props.navigation.addListener('willFocus',
      Auth.me().then(async (response) => {
        await this.setState({ isLoggedIn: response });
      }));
}

...
}

Auth.js

import axios from 'axios';
import { ENV } from 'app/env';
import { AsyncStorage } from 'react-native';

const { baseApiUrl } = ENV;

export default {
  async me() {
    try {
      let result = false;
      let token = await AsyncStorage.getItem('token');
      token = token.replace(/"/g, '');
      const response = await axios.get(`${baseApiUrl}/api/auth/me`, {
        headers: {
          Authorization: `Bearer ${token}`,
        },
      });
      if (response.data) {
        result = true;
      }
      return result;
    } catch (error) {
      console.log(error);
    }
  },

};


错误

我一直收到这个错误。

TypeError: cb is not a function. (In 'cb(data)', 'cb' is an instance of Promise)

如果您能给我任何建议,我将不胜感激。

如果不了解您的代码(或反应)的详细信息,很难说清楚,但从名称上我希望 this.props.navigation.addListener 具有 callback 功能。相反,你传递了一个承诺。

this.props.navigation.addListener('willFocus',
  Auth.me().then(async (response) => {
    await this.setState({ isLoggedIn: response });
  })
);

尝试将代码更改为:

this.props.navigation.addListener('willFocus', () => {
  Auth.me().then(async (response) => {
    await this.setState({ isLoggedIn: response });
  })
});

编辑:@kai 对当前问题的回答更好(并且正确)。不过我会留下答案,无论如何在 setState 函数上使用 async/await 是错误的

您应该从 setState 中删除 await

this.props.navigation.addListener('willFocus',
  Auth.me()
    .then((response) => {
      this.setState({ isLoggedIn: response });
    })
);

通过使用 await,Javascript 需要 Promise。但是 this.setState 没有 return 函数。


旁注,如果您需要等待应用 setState 函数,您可以使用回调作为第二个参数:

this.setState({ data }, () => console.log("Now the new state has been applied!"))