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(){}
 

  


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM