JavaScript中子向父组件回调报错:Cannot read property 'push' of undefined
解决"Cannot read property 'push' of undefined"在ModelState.dirtyListCallback中的问题
这个错误其实很典型——本质是你在dirtyListCallback方法里尝试调用push的目标数组(大概率是dirtyList)要么没被初始化,要么方法执行时的this指向跑偏了,导致访问不到实例上的数组属性。我帮你梳理两种最可能的原因和对应修复方案:
1. ModelState类未初始化目标数组
如果你的ModelState构造函数里压根没创建dirtyList数组,那当dirtyListCallback尝试往它里面push元素时,自然会得到undefined。
修复方法:在ModelState的构造函数里初始化这个数组:
class ModelState { constructor() { // 初始化dirtyList为空数组 this.dirtyList = []; } dirtyListCallback(scene) { // 现在push就不会报错了 this.dirtyList.push(scene); } }
2. 回调函数的this指向错误
另一种常见情况是,当LabScene调用currentState.dirtyListCallback时,这个方法的this没有绑定到currentState实例上,导致this.dirtyList变成了undefined。
这种情况有几种修复方式:
方式一:在构造函数里绑定this
class ModelState { constructor() { this.dirtyList = []; // 绑定this到实例,确保回调时指向正确 this.dirtyListCallback = this.dirtyListCallback.bind(this); } dirtyListCallback(scene) { this.dirtyList.push(scene); } }
方式二:使用箭头函数定义回调方法
箭头函数会自动继承外层的this,避免指向问题:
class ModelState { constructor() { this.dirtyList = []; } // 用箭头函数定义方法 dirtyListCallback = (scene) => { this.dirtyList.push(scene); } }
方式三:在传递回调时绑定this
如果是在创建LabScene实例时传递回调,直接绑定:
function main(){ var currentState = new ModelState(); // 传递回调时绑定currentState的this var scene = new LabScene(() => currentState.dirtyListCallback(scene)); }
你可以先检查下ModelState的构造函数有没有初始化数组,再确认回调时的this指向是否正确,应该就能解决这个问题了。
内容的提问来源于stack exchange,提问作者BPoy
相关产品推荐
相关产品推荐

