undefinend 不是函数 this.setState react native

undefinend is not a function this.setState react native

我正在开发一个 React Native 应用程序。当我尝试执行以下代码时出现错误。但是同一文件其他部分的 setStates 工作正常。

undefined is not a function(evaluating'this.setState({firebaseMessages: "Wrong password"})

 .catch(function(error) {
    var errorCode = error.code;
    var errorMessage = error.message;

    if (errorCode === "auth/wrong-password") {
      //alert("Wrong password.");
      this.setState({ firebaseMessages: "Wrong password" });
      this.setState({ isModalVisibleFirebase: true });
      this.setState({ loading: false })
      return;
    } else {
      alert(errorMessage);
      return;
    }
    console.log(error);
  }

您可能需要绑定回调函数,试试这个:

catch(function(error) {
    var errorCode = error.code;
    var errorMessage = error.message;

    if (errorCode === "auth/wrong-password") {
        //alert("Wrong password.");
        this.setState({ firebaseMessages: "Wrong password" });
        this.setState({ isModalVisibleFirebase: true });
        this.setState({ loading: false })
        return;
    } else {
        alert(errorMessage);
        return;
    }
    console.log(error);
}.bind(this)) // change this line

或者,您可以使用 ES6 箭头函数,如下所示:

catch((error) => {  // change this line
    var errorCode = error.code;
    var errorMessage = error.message;

    if (errorCode === "auth/wrong-password") {
        //alert("Wrong password.");
        this.setState({ firebaseMessages: "Wrong password" });
        this.setState({ isModalVisibleFirebase: true });
        this.setState({ loading: false })
        return;
    } else {
        alert(errorMessage);
        return;
    }
    console.log(error);
})

如果您使用 ES5 函数定义方式,您的 this 范围将会改变,请使用箭头语法来保持 this 范围。

所以现在你应该 .catch((error) => { 而不是 .catch(function (error){

.catch((error) => {
    var errorCode = error.code;
    var errorMessage = error.message;

    if (errorCode === "auth/wrong-password") {
      //alert("Wrong password.");
      this.setState({ firebaseMessages: "Wrong password" });
      this.setState({ isModalVisibleFirebase: true });
      this.setState({ loading: false })
      return;
    } else {
      alert(errorMessage);
      return;
    }
    console.log(error);
  }

简单的解决方案是,将 this 分配给某个变量,然后使用该变量调用 setState

const _this = this; //write this before fetch method

然后像这样使用,

_this.setState({ firebaseMessages: "Wrong password" });