首页 > 解决方案 > undefined 不是对象(评估 '_this2.getInfoFromToken')

问题描述

我在这里的类组件中编写了两个函数

facebooklogin = () => {
    console.log('fblogin');
    LoginManager.logInWithPermissions(['email', 'public_profile']).then(
      function (result) {
        if (result.isCancelled) {
          console.log('Login cancelled');
        } else {
          console.log(
            'Login success with permissions: ' +
            result.grantedPermissions.toString(),
          );
          AccessToken.getCurrentAccessToken().then(data => {
            // console.log(data);
            // console.log(data.accessToken.toString());
            const accessToken = data.accessToken.toString();
            this.getInfoFromToken(accessToken);
          });
        }
      },
      function (error) {
        console.log('Login fail with error: ' + error);
      },
    );
  };
getInfoFromToken = token => {
console.log(token);
},

当我调用 facebooklogin() 时,它显示此错误可能未处理的 Promise Rejection (id: 4): TypeError: undefined is not an object (evaluating '_this2.getInfoFromToken')

标签: react-native

解决方案


调用时this.getInfoFromToken(accessToken);,您尝试this从 a访问function,在严格模式下等于undefined

您可以尝试将其设置为箭头函数,这将使内部this引用适用于 contextual this,这似乎是上面代码中的目的。

您只需要更改第 4 行:

      function (result) {

对于箭头函数声明:

      (result) => {

它行得通吗?

此外,您可能希望向 Promise 链添加一个.catch()回调AccessToken.getCurrentAccessToken()(如果它返回一个类似 Promise 的对象,看起来如此)。


推荐阅读