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

正常定义全局变量:

data:function (){
      return{
        currentOrders:[]
      }
    },

  使用Axios发送请求并获取后端数据时,如果在then中使用this.currentOrders会出现TypeError: Cannot set property 'xxxx' of undefined错误。

  原因是使用this$axios().then(function(response){}).catch()格式获取参数,then的内部 this 没有被绑定,所以不能使用Vue的实例化的this。

  解决办法一:在this.$axios外部将this赋值为自定义变量:var that = this,然后在then里面使用that.currentOrders

var that = this
      this.$axios({
        method: 'get',
        url: 'xxxxxx',
      }).then(function (response) {
        var jsonObj = JSON.parse(JSON.stringify(response.data))
        if (jsonObj.code === ERR_ok){
          that.currentOrders = jsonObj.data
        }
      }).catch(function (error) {
        console.log(error);
      })

第二种方法:用ES6箭头函数,箭头方法可以和父方法共享变量

this.$axios({
        method: 'get',
        url: 'xxxxxx',
      }).then((response)=>{})
      .catch(){}
 

  

原文地址:https://www.cnblogs.com/xjtsh/p/12887829.html