首页 > 解决方案 > 在 React.js 中使用异步回调函数时无法读取状态

问题描述

因此,我从 stackoverflow 的帖子中复制了此功能,我的目标是能够在注册后立即更新数据库和配置文件信息,然后再转到其他路线,结果与我预期的一样有效,但我无法再访问回调中的状态,请有人帮我调试这段代码:

  signup = (e) => {
    this.setState({ loading: true });
    e.preventDefault();
    fire.auth().createUserWithEmailAndPassword(this.state.email, this.state.password)
      .then((userCredentials) => {
        if (userCredentials.user) {
          userCredentials.user.updateProfile({
            displayName: this.state.username,
            photoURL: 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQdVmHPt9SajdsWlAZWzqRXkd-SzmmO9bBUV45fLnw5giijsty3OA',
          }).then((s) => {
            fire.database()
              .ref(`master/${userCredentials.user.displayName}/setup/`)
              .update({
                bio: 'Be original',
              })
              .then(() => {
                window.location.reload();
              });
          })
        }
      })
      .catch(function (error) {
        console.log(error);
        this.setState({ signupError: true, loading: false, });
      });
  }

错误发生在 catch(error)

TypeError:无法读取未定义的属性“setState”

我怀疑问题来自使用多个.then

标签: javascriptreactjs

解决方案


thisincatch不是您的班级,请查看普通功能和箭头功能之间的区别。有两种方法可以解决您的问题。

  • 第一:使用箭头函数
.catch(function (error) {
  console.log(error);
  this.setState({ signupError: true, loading: false, });
});
  • 第二:设置局部self变量为this
signup = (e) => {
  this.setState({ loading: true });
  e.preventDefault();
  const self = this; // It can be what ever you want, `self` is the most popular
  ...
}

然后

.catch(function (error) {
  console.log(error);
  self.setState({ signupError: true, loading: false, });
});

推荐阅读