Cannot read properties of undefined (reading 'xxx')。解决Vue中axios回调函数this指向问题的方法

1,074 阅读1分钟

在Vue开发中,我们经常会使用axios库来进行网络请求。然而,有时候在axios的回调函数中使用this时,可能会遇到Cannot read properties of undefined (reading 'xxx')这样的错误,这是由于回调函数的上下文问题导致的。

在本篇博客中,我们将介绍两种解决这个问题的方法,确保在axios回调函数中正确访问Vue组件的属性和方法。

方法一:使用箭头函数

箭头函数是ES6中的新特性,它没有自己的上下文,而是继承外部的上下文。因此,在回调函数中使用箭头函数可以解决上下文问题。

changeStatus(row) {
  const id = row.commissionId;
  const type = '黄金';
  axios.post('http://localhost:8080/api/deposit/changeStatus', null, {
    params: {
      id: id,
      type: type,
    },
  })
  .then((response) => {
    this.$message({
      type: 'success',
      message: '兑换成功',
    });
    // 状态改变后刷新数据表格
    this.getListExchangeRecord();
  })
  .catch((error) => {
    console.log(error);
  });
},

方法二:保存this的引用

changeStatus方法中,我们可以将this保存在另一个变量中,然后在回调函数中使用该变量来访问Vue组件。

changeStatus(row) {
  const id = row.commissionId;
  const type = '黄金';
  const vm = this; // 保存this的引用
  axios.post('http://localhost:8080/api/deposit/changeStatus', null, {
    params: {
      id: id,
      type: type,
    },
  })
  .then(function (response) {
    vm.$message({
      type: 'success',
      message: '兑换成功',
    });
    // 状态改变后刷新数据表格
    vm.getListExchangeRecord();
  })
  .catch(function (error) {
    console.log(error);
  });
},

通过这两种方法,我们可以成功解决axios回调函数中this指向的问题,确保在Vue组件中正确使用this,避免出现未定义的错误。同时,在状态改变后也能正确刷新数据表格,提升用户体验。

希望本篇博客能帮助到你解决Vue中axios回调函数this指向问题,欢迎分享给更多的开发者!