首页 > 解决方案 > 无法使用 axios 设置状态

问题描述

componentDidMount() {
  var self = this;

  axios.get('http://URL')
    .then(function (response) {
      console.log(response.data);
      this.setState({
        data: response.data
      })
    })
    .catch(function (error) {
      console.log(error);
    });
}

我收到此错误:TypeError: Cannot read property 'setState' of undefined

标签: javascriptreactjsaxios

解决方案


使用箭头函数,这样你就不需要依赖局部变量了,作用域会被自动处理

 componentDidMount(){
     axios.get('http://URL')
         .then( response => {
            console.log(response.data);
            this.setState({data: response.data})
     })
    .catch(error =>  {
        console.log(error);
   });
 }

或者在执行 setState 时将其替换为 self ,如下所示

  componentDidMount(){
      var self = this;
      axios.get('http://URL')
         .then(function (response) {
             console.log(response.data);
             self.setState({data: response.data})
     })
    .catch(function (error) {
       console.log(error);
    });
  }

以上两个选项都可以。我建议你选择第一个选项


推荐阅读