Vue调用save方法时报错errorList未定义该如何解决?
Vue报错TypeError: Cannot read property 'errorList' of undefined 解决方案
报错原因
你在Array.filter()的回调中使用了普通匿名函数,普通函数会绑定独立的this指向,在严格模式下该回调的this默认值为undefined,因此无法访问到Vue实例上的errorList属性,触发报错。
可行修复方案
你可以任选以下任意一种方案修改代码:
- 方案1:将回调替换为箭头函数
箭头函数不会绑定独立的this,会继承外层save方法的this指向(也就是Vue实例),修改后代码如下:
save(e) { e.preventDefault(); this.general.learnings.filter((el) => { if (el !== "") { return true; } else { this.errorList.push("Error"); } }); }
- 方案2:外层缓存this指向
在回调外提前将Vue实例的this存储到临时变量中,回调内使用临时变量访问属性:
save(e) { e.preventDefault(); // 缓存Vue实例指向 const vm = this; this.general.learnings.filter(function (el) { if (el !== "") { return true; } else { vm.errorList.push("Error"); } }); }
- 方案3:给filter传入this指向参数
Array.filter支持传入第二个参数作为回调函数的this指向,直接传入当前this即可:
save(e) { e.preventDefault(); this.general.learnings.filter(function (el) { if (el !== "") { return true; } else { this.errorList.push("Error"); } }, this); // 第二个参数指定回调的this为当前Vue实例 }
代码优化建议
当前场景你只需要遍历数组收集错误,没有用到filter返回的过滤后数组,建议使用语义更匹配的Array.forEach来做遍历,代码可读性更高。
内容的提问来源于stack exchange,提问作者Synchro
相关产品推荐
相关产品推荐

