首页 > 解决方案 > 如何修复未捕获(承诺中)TypeError:无法设置未定义的属性

问题描述

当我想将 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

解决方案


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

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


推荐阅读