【问题标题】:Calling a function inside .then() is throwing an error在 .then() 中调用函数会引发错误
【发布时间】:2018-11-06 11:09:33
【问题描述】:

我正在尝试使用 firebase 执行一些任务,并在没有任何回调函数的情况下在 Promise 中调用一些函数,这给了我一个错误。 这是我的代码

onButtonPress = () => {
  const {email, password} = this.state
  this.setState({error: '', loading: true});

  firebase.auth().signInWithEmailAndPassword(email, password)
  .then(this.onAuthSuccess().bind(this))
  .catch(()=>{
    firebase.auth().createUserWithEmailAndPassword(email, password)
    .then(this.onAuthSuccess().bind(this))
    .catch(this.onAuthFailed().bind(this))
  })
}

  onAuthSuccess() {
    this.setState({
      email: '',
      password: '',
      error: '',
      loading: false
    })
  }

  onAuthFailed() {
    this.setState({
      error: "Authentication Failed",
      loading: false
    })
  }

这是我收到的错误消息

undefined 不是对象(评估 '_this.onAuthSuccess().bind()')

【问题讨论】:

  • 你想要this.onAuthSuccess.bind(this),而不是this.onAuthSuccess().bind(this)onAuthFailed 也一样)。 bind 是函数的方法!

标签: firebase react-native promise firebase-authentication


【解决方案1】:

在 ES6 中处理this 上下文的三种方式。

  1. 使用bind关键字
onAuthSuccess() {
    ...
}

firebase.auth()
    .then(this.onAuthSuccess.bind(this));
    .catch(this.onAuthFailed.bind(this));
}
  1. 使用箭头函数避免预绑定
onAuthSuccess = () => {
    ...
}

firebase.auth()
    .then(this.onAuthSuccess);
    .catch(this.onAuthFailed);
}
  1. 在构造函数中绑定你的方法
constructor(props) {
    super(props);
    this.onAuthSuccess = this.onAuthSuccess.bind(this);
}

【讨论】:

    【解决方案2】:

    不是 100%,因为好的 ol this 上下文令人困惑!

    所以我认为您想摆脱 bind() 并在您的函数上使用 =>。使用粗箭头将重置this 的上下文,因此this.setState 应该在基于类的组件的上下文中正确。

    这是我的意思的一个例子

    onAuthSuccess = () => {
      this.setState({
        email: "",
        password: "",
        error: "",
        loading: false
      });
    };
    
    onAuthFailed = () => {
      this.setState({
        error: "Authentication Failed",
        loading: false
      });
    };
    
    onButtonPress = () => {
      const { email, password } = this.state;
      this.setState({ error: "", loading: true });
    
       firebase
      .auth()
      .signInWithEmailAndPassword(email, password)
      .then(() => this.onAuthSuccess())
      .catch(() => {
        firebase
          .auth()
          .createUserWithEmailAndPassword(email, password)
          .then(() => this.onAuthSuccess())
          .catch(() => this.onAuthFailed());
      });
    };
    

    【讨论】:

    • 调用函数而不是传递它们仍然是错误的
    • 我刚刚检查了一下..你确定你的firebase函数是正确的吗?我已经用我认为正确的方法更新了我的答案.then()
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-23
    • 1970-01-01
    • 2021-02-19
    • 2020-11-15
    相关资源
    最近更新 更多