【问题标题】:How to fix Uncaught (in promise) TypeError: Cannot set property of undefined如何修复未捕获(承诺)TypeError:无法设置未定义的属性
【发布时间】:2021-01-19 22:11:35
【问题描述】:

我想将API结果中的值发送到数据时出现错误,错误是这样的

Uncaught (in promise) TypeError: Cannot set property 'notification' of undefined at eval (HeaderPortal.vue?070f:367)

这是我的 HeaderPortal.vue

    data() {
      return {
        notification: []
      }
    }
    methods: {
        const res = this.GET('/api/v2/notification', 'BEARER', null).then( function(res) {
          console.log(JSON.parse(res))
          this.notification = JSON.parse(res);
        });
    }

this.GET 来自这里

methods: {
        async GET(url, headers, callback) {
            const options = headers === 'BASIC' ? HEADERS_BASIC : HEADERS_BEARER;
            try {
                const response = await axios.get(`${BASE_URL}${url}`, options);
                return (JSON.stringify(response));
            } catch (e) {
                console.error(e);
            }
        },
}

如何处理?我的代码有问题吗?

【问题讨论】:

    标签: nuxt.js


    【解决方案1】:

    如果您需要访问 this 关键字,请确保在回调中使用箭头函数 () => {} 而不是常规函数 function() {}。如果你不这样做,this 关键字将是 undefined 在你的情况下。这就是您尝试在第一个代码 sn-p 中设置 this.notification = JSON.parse(res); 时遇到错误的原因。

    你的第一个代码 sn-p 有点奇怪,也许你忘了复制一些东西?您的代码不应直接位于方法对象内。它应该在挂载的钩子中,或者在第二个 sn-p 中的适当方法中。

    【讨论】:

      【解决方案2】:

      内部函数中的this 仅指函数,因此它不起作用。相反,写:

      s=this;
      const res = this.GET('/api/v2/notification', 'BEARER', null).then( 
      function(res) {
            console.log(JSON.parse(res))
            s.notification = JSON.parse(res);
          });
      }
      

      【讨论】:

      • 这是否为近一年前的上一个答案添加了任何新内容?
      • 是的,在某种程度上,因为在新答案中解决了“this”应该如何改变
      【解决方案3】:

      答案很清楚,让我用例子来说明一下:

      data() {
            return {
              notification: []
            }
          }
          methods: {
              const res = this.GET('/api/v2/notification', 'BEARER', null).then( res =>  {
                console.log(JSON.parse(res))
                this.notification = JSON.parse(res);
              });
          }
      

      希望对你有用

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-12-24
        • 2019-05-16
        • 2018-05-28
        • 1970-01-01
        • 1970-01-01
        • 2018-06-11
        • 2019-05-31
        • 2017-03-04
        相关资源
        最近更新 更多