【问题标题】:Uncaught (in promise) TypeError: Cannot set property of undefined at eval in vue.js?Uncaught (in promise) TypeError: Cannot set property of undefined at eval in vue.js?
【发布时间】:2019-11-26 08:33:45
【问题描述】:

我正在尝试使用从我的服务器 API 获得的值设置我的空对象,这是一个 json。 但是我在同一行一遍又一遍地收到错误:

Uncaught (in promise) TypeError: Cannot set property 'itemListModel' of undefined at eval

我的代码:

data: function() {
return {
itemListModel: {}
}
}

methods: {
   getAllItemsFromDb: async () => {
    const url = 'https://localhost:44339/ListAll';
      await axios.get(url, {
    headers: {
        'Content-Type': 'application/json'
    }}).then((response) => {
         this.itemListModel = response.data
    })
    }
}

computed : {
   itemResultsFromDB: function(){

      return this.itemListModel
    }
}

看了这个之前的问题:Uncaught (in promise) TypeError: Cannot set property of undefined with axios

但我看不出我在做什么不同?

【问题讨论】:

  • 在您链接答案的问题中,在调用axios 之前添加let self = this,然后使用变量selfaxios.get() 中引用它,因为this 在某处被重新定义跨度>
  • 如何调用getAllItemsFromDb 方法?

标签: javascript vue.js axios


【解决方案1】:

我相信箭头功能是罪魁祸首。将 getAllItemsFromDb 转换为 function 函数:

methods: {
   getAllItemsFromDb() {
      const url = 'https://localhost:44339/ListAll';

      axios.get(url, {
         headers: {
            'Content-Type': 'application/json'
         }
      }).then((response) => {
         this.itemListModel = response.data
      })
   }
}

【讨论】:

  • 谢谢,这就是问题所在,它解决了我的问题!
【解决方案2】:

在您的 getAllItemsFromDb 函数中,您正在等待 axios.get() 的结果。因此,您不需要 .then() 块。试试这个:

getAllItemsFromDb: async () => {
  const url = 'https://localhost:44339/ListAll';
  const response = await axios.get(url, {
    headers: {
      'Content-Type': 'application/json'
    }
  });

  this.itemListModel = response.data;
}

【讨论】:

    猜你喜欢
    • 2018-01-26
    • 2018-05-07
    • 2018-01-24
    • 1970-01-01
    • 1970-01-01
    • 2019-02-12
    • 2021-09-20
    • 2021-06-08
    • 1970-01-01
    相关资源
    最近更新 更多