Ember JS往数组添加对象时报Cannot read property 'tags' of undefined如何解决
问题原因
你遇到的Cannot read property 'tags' of undefined报错核心原因是forEach回调的this指向错误:
你给this.selectedEntities.forEach传入了普通匿名函数,这类函数不会继承外层openTestModal方法的this指向,在Ember类的严格模式运行环境下,函数内部this值为undefined,尝试访问undefined.tags就会触发对应报错。
解决方案
你可以任选下面一种方法修复指向问题:
方案1:将forEach的回调替换为箭头函数(最常用)
箭头函数会自动继承外层作用域的this,不需要额外处理指向,修改后代码参考如下:
@action openTestModal() { // 把原本的function(e)替换为箭头函数写法(e) => this.selectedEntities.forEach((e) => { console.log("name ", e.contactInfo.contactName); console.log("e.id ", e.id); if(e.workflowTask !== null){ console.log("e.workflowTask.currentStatus ", e.workflowTask.currentStatus); const tag = { id: e.id, name: e.contactInfo.contactName, status: e.workflowTask.currentStatus }; this.tags.pushObject(tag); } const tag = { id: e.id, name: e.contactInfo.contactName, status: e.workflowTask?.currentStatus }; this.tags.pushObject(tag); }); this.remodal.open('user-assign'); }
方案2:给forEach传入第二个参数指定this指向
Array.prototype.forEach原生支持传入第二个参数,作为回调函数内部的this取值,你可以直接把外层的控制器实例this传进去:
// 仅需修改forEach调用部分,内部代码无需改动 this.selectedEntities.forEach(function (e){ // 原有逻辑保持不变 }, this) // 新增第二个参数传入外层this
方案3:提前存储控制器实例到临时变量
你也可以在进入forEach循环前,把控制器实例this赋值给一个临时变量,回调内通过这个临时变量访问属性:
@action openTestModal() { const that = this; // 提前存储控制器实例 this.selectedEntities.forEach(function (e){ // 把原来所有的this.tags替换为that.tags即可 that.tags.pushObject(tag); }) }
额外逻辑提示
你现有代码中if分支外的tag创建逻辑没有判断e.workflowTask是否为null,当e.workflowTask为null时直接访问e.workflowTask.currentStatus会触发新的空值报错,建议要么把这段逻辑移到if判断内部,要么用可选链操作符?.做空值兼容。
内容的提问来源于stack exchange,提问作者dasitha
相关产品推荐
相关产品推荐

