Cannot setState in axios.post, react native

时间:2018-01-15 18:10:46

标签: android ios react-native

Here's my constructor

constructor(props) {
  super(props)
  this.state = {
    email: '',
    resetSuccess: true
  };
  //this.forgotPassword = this.forgotPassword.bind(this);
}

.. and here's my function

forgotPassword = () => {
  axios.post('http://10.0.2.2:8000/api/forgotPassword', {
      email: this.state.email,
    })
    .then(function (response, data) {
      console.log(response.data.success);
      if(response.data.success == false) {
        this.setState({resetSuccess:false})
      } else {
        //navigate('PasswordSent')
      }
    })
    .catch(function (error) {
      console.log(error);
    });
  }

Here's the error that I'm getting when the API returns false and setState is called.

undefined is not a function (evaluating 'this.setState({ resetSuccess: false })')

I've left in the commented out 'this.forgotPassword = this.forgotPassword.bind(this)' in the constructor; if I uncomment that there's no difference in the error that is returned.

UPDATE SOLVED

I was able to solve this issue by updating the forgotPassword funciton with: var self = this;

forgotPassword = () => {
  var self = this;
  axios.post('http://10.0.2.2:8000/api/forgotPassword', {
  email: this.state.email,
})
.then(function (response, data) {
  console.log(response.data.success);
  if(response.data.success == false) {
    this.setState({resetSuccess:false})
  } else {
    //navigate('PasswordSent')
  }
})
.catch(function (error) {
  console.log(error);
});

}

1 个答案:

答案 0 :(得分:0)

尝试使用“箭头功能”代替“功能”,然后避免“自我”解决方案。