开发者问题收集

未处理的承诺拒绝未定义

2017-08-03
4301

在我的 React Native 应用中,我有一个自定义登录 Facebook 按钮:

<Button onPress={() => this.handleFacebookLogin()}>
  <Text>Login with Face</Text>
</Button>

以及 handleFacebookLogin 函数:

 handleFacebookLogin () {
     LoginManager.logInWithReadPermissions(['public_profile', 'email', 'user_friends']).then(
       function (result) {
         if (result.isCancelled) {
           console.log('Login cancelled')
         } else {
           console.log('Login success with permissions: ' + result.grantedPermissions.toString())
           AccessToken.getCurrentAccessToken().then(
             (data) => {
               signInFacebookLoginInFirebase(data.accessToken)
               //this.signInFacebookLoginInFirebase(data.accessToken)
             }
           )
         }
       },
       function (error) {
         console.log('Login fail with error: ' + error)
         alert('Error at login, no network ?')
       }
     )
 }

但是我收到此错误:

Possible Unhandled Promise Rejection (id: 20): ReferenceError: signInFacebookLoginInFirebase is not defined TypeError: _this2.signInFacebookLoginInFirebase is not a function

TypeError:_this2.signInFacebookLoginInFirebase 不是函数

以及 signInFacebookLoginInFirebase 方法:

   signInFacebookLoginInFirebase(facebookToken){
     const credential = Fb.firebase.auth.FacebookAuthProvider.credential(facebookToken);
     Fb.firebase
       .auth()
       .signInWithCredential(credential)
       .then(() => alert('Account accepted'))
       .catch((error) => alert('Account disabled'));
   }
1个回答

由于未在 .then 回调 logInWithReadPermissions 中使用箭头符号, this 将不会成为 signInFacebookLoginInFirebase 函数的上下文

您在 AccessToken.getCurrentAccessToken().then 中使用箭头符号,因此这样很好,现在您只需将

LoginManager.logInWithReadPermissions(['public_profile', 'email', 'user_friends']).then(
    function (result) {

更改为

LoginManager.logInWithReadPermissions(['public_profile', 'email', 'user_friends']).then(
    (result) => {

然后使用注释掉的

this.signInFacebookLoginInFirebase(data.accessToken);

为了正确处理所有潜在的拒绝,我建议

handleFacebookLogin () {
    LoginManager.logInWithReadPermissions(['public_profile', 'email', 'user_friends'])
    .then(result => {
        if (result.isCancelled) {
            console.log('Login cancelled');
        } else {
            console.log('Login success with permissions: ' + result.grantedPermissions.toString())
            return AccessToken.getCurrentAccessToken()
            .then(data => this.signInFacebookLoginInFirebase(data.accessToken));
        }
    // .catch chained from .then to handle all rejections
    }).catch(error => {
        console.log('Login fail with error: ' + error);
        alert('Error at login, no network ?');
    })
}
Jaromanda X
2017-08-03