VUE使用axios数据请求时报错 TypeError: Cannot set property 'xxxx' of undefined 的解决办法

正常情况下在data里面都有做了定义

data(){
    return {
       list:[]
    }
  },

在函数里面进行赋值

this.list=response.data.data;

这时候你运行时会发现,数据可以请求到,但是会报错TypeError: Cannot set property 'list' of undefined

主要原因是:

在 then的内部不能使用Vue的实例化的this, 因为在内部 this 没有被绑定。

解决办法:

1、用ES6箭头函数,箭头方法可以和父方法共享变量

axios.get('url').then((response)=>{
      // console.log(response.data.data);
      this.list=response.data.data;
      console.log(this.list);
    }).catch(function(error){
      console.log(error);
    });

2、在请求axios外面定义一下 var that=this

created(){
    console.log("页面加载完成");
    var that=this;
 
    axios.get('url').then(function(response){
      that.list=response.data.data;
      console.log(that.list);
    }).catch(function(error){
      console.log(error);
    });
  }
原文地址:https://www.cnblogs.com/Strugglinggirl/p/14059152.html