Angular学习遇到报错:Cannot read properties of undefined (reading 'push')
Angular学习遇到报错:Cannot read properties of undefined (reading 'push')
嘿,我一眼就揪出问题所在啦!这个报错的核心原因是函数调用时this的指向不对,别着急,我给你拆解清楚并提供几种顺手的解决办法:
问题根源
当你在onStartGame里用setInterval(this.GameStarted,1000)的时候,GameStarted是作为普通函数被调用的,这时候函数内部的this指向的是全局对象(浏览器环境下是window),而不是你的GameControlComponent组件实例。所以this.even和this.unEven都会变成undefined,调用push方法自然就会抛出你看到的错误。
解决办法
这里有三种常用的修复方式,选你觉得顺手的就行:
方法1:用箭头函数包裹回调
箭头函数会继承外部作用域的this,这样就能确保GameStarted里的this稳稳指向组件实例:
onStartGame(){ this.intervalID = setInterval(() => this.GameStarted(), 1000) }
方法2:提前绑定this到组件实例
可以在构造函数里把GameStarted的this绑定到组件,这样无论怎么调用这个函数,this都不会“跑丢”:
constructor() { this.GameStarted = this.GameStarted.bind(this); } // 原来的onStartGame不用改 onStartGame(){ this.intervalID = setInterval(this.GameStarted,1000) }
或者直接在setInterval里临时绑定:
onStartGame(){ this.intervalID = setInterval(this.GameStarted.bind(this), 1000) }
方法3:把GameStarted定义成箭头函数方法
直接把组件方法写成箭头函数形式,这样它的this会永久绑定到组件实例,再也不用操心指向问题:
GameStarted = () => { this.counter = this.counter + 1; Number.isInteger(this.counter/2) ? this.even.push(this.counter) : this.unEven.push(this.counter); console.log('Even numbers logged: '+ this.even); console.log('Uneven numbers logged: '+ this.unEven); } // 原来的onStartGame不用改 onStartGame(){ this.intervalID = setInterval(this.GameStarted,1000) }
验证效果
随便选一种方法改完后,再启动游戏,this.even和this.unEven就能正常访问并调用push方法,你的奇偶数字分类逻辑就能顺畅跑起来啦!
备注:内容来源于stack exchange,提问作者Bart Koolhaas
相关产品推荐
相关产品推荐

