后端开发学前端不要怕,学习成本并不高,不工作了还可独立接私活。关注本专栏,让你不自觉的学会了前端开发知识。
本文章列举了3个知识点的问答。
1,vue2 如果执行这行代码报错 :Uncaught TypeError: this is undefined 是为什么?
this.$refs['rskchart' + i + '1'].showNoData();
这个错误是因为 this 的上下文(context)丢失了,this 变成了 undefined。在 JavaScript 中,this 的值取决于函数的调用方式。
常见原因和解决方案:
1. 在回调函数或异步函数中丢失上下文(最常见)
// ❌ 错误:在回调中丢失 this
setTimeout(function() {
this.$refs['rskchart' + i + '1'].showNoData(); // this 是 undefined
}, 1000);
// ✅ 解决方案1:使用箭头函数(保留外部 this)
setTimeout(() => {
this.$refs['rskchart' + i + '1'].showNoData();
}, 1000);
// ✅ 解决方案2:提前保存 this
const self = this;
setTimeout(function() {
self.$refs['rskchart' + i + '1'].showNoData();
}, 1000);
// ✅ 解决方案3:使用 bind
setTimeout(function() {
this.$refs['rskchart' + i + '1'].showNoData();
}.bind(this), 1000);
2. 在数组方法中丢失上下文
// ❌ 错误:在 forEach 中丢失 this

最低0.47元/天 解锁文章
1217

被折叠的 条评论
为什么被折叠?



