nuxt.js - 如何修复未捕获(承诺中)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);
}
},
}
如何处理?我的代码有问题吗?
解决方案
如果您需要访问this
关键字,请确保在回调中使用箭头函数() => {}
而不是常规函数。function() {}
如果你不这样做,this
关键字将undefined
在你的情况下。这就是您尝试this.notification = JSON.parse(res);
在第一个代码段中设置错误的原因。
你的第一个代码片段有点奇怪,也许你忘了复制一些东西?您的代码不应直接位于方法对象内。它应该在挂载的钩子中,或者在第二个片段中的适当方法中。
推荐阅读
- ios - 使用来自 Web 服务的更新数据(包括关系)更新核心数据
- reactjs - ReactJS 中图片的相对路径
- javascript - 为什么节点 https 模块文档示例将 tls 选项同时传递给代理和请求选项?
- flutter - 颤振统一小部件是否适用于统一 2d?
- javascript - 仅获取具有两个特定类的 div
- python - 修改 dtypes 的输出
- javascript - Firebase 响应太慢
- python - 如何判断 Firestore 中刚刚添加了哪个文档?
- php - PDO 插入数组只显示一个条目
- c# - EF Core 一对多按导航属性(不是按主键)