不能使用axios setState

问题描述 投票:1回答:4
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:无法读取undefined的属性'setState'

javascript reactjs axios
4个回答
1
投票

使用箭头功能,您无需依赖局部变量和范围将自动处理

 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);
    });
  }

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


0
投票

如果你在setState上使用self而不是this应该修复。


0
投票

您可以使用ES6箭头函数自动绑定词汇父作用域。

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

            this.setState({
                data: response.data
            })
     })
    .catch(error =>  {
        console.log(error);
   });
 }

介绍self是过度的,来自jQuery。它是在引入ES6箭头功能之前使用的。

你可以在这里阅读箭头函数中的自动this绑定:

https://hackernoon.com/javascript-es6-arrow-functions-and-lexical-this-f2a3e2a5e8c4

还要检查这些链接,以便更好地了解this在Javascript中的工作原理以及范围逻辑:

https://scotch.io/tutorials/understanding-scope-in-javascript https://javascriptplayground.com/javascript-variable-scope-this/


0
投票

您可以避免this上下文问题并使用此替代方法。由于Axios返回一个promise,你可以使用async / await,而不考虑this上下文。

像这样使用它:

async function getData(url){
    try {
        return await axios.get(url);
    } catch(error) {
        console.log(error);
    }
}

async componentDidMount(){
    let response = await getData('http://URL');
    console.log(response.data);
    this.setState({data: response.data});
 }

对于其他功能和组件,它看起来更易读,更易于使用。

© www.soinside.com 2019 - 2024. All rights reserved.