TypeScript中判断变量是否未定义时出现Cannot read properties of undefined错误
回调函数中this指向丢失导致的属性读取错误解决
问题场景
你在TypeScript函数中编写了以下代码,其中variableInQuestion = 0定义在函数外部:
console.log(this.variableInQuestion); this.arrayOfObjects.each(function(thing) { if (this.variableInQuestion !== undefined && thing.property == this.variableInQuestion) { // ... } });
运行时,外层的console.log能正常输出默认值0,但回调函数内的代码报错:Cannot read properties of undefined (reading 'variableInQuestion')。将代码中的this.variableInQuestion替换为硬编码的0后,代码可正常运行。
问题原因
核心问题是普通函数作为回调时,会改变this的指向:
- 外层函数中的
this指向包含variableInQuestion的上下文; - 但在
each方法的普通function回调里,this的绑定会被修改(严格模式下会变成undefined,非严格模式下指向全局对象)。此时你尝试读取this.variableInQuestion,本质是在undefined上读取属性,自然触发报错——你写的this.variableInQuestion !== undefined的前提是this本身存在,现在this已经是undefined,第一步访问属性就失败了。
解决方案
1. 使用箭头函数
箭头函数不会绑定自身的this,会继承外层作用域的this,完美适配这种场景:
console.log(this.variableInQuestion); this.arrayOfObjects.each((thing) => { if (this.variableInQuestion !== undefined && thing.property == this.variableInQuestion) { // ... } });
2. 提前保存外层this到变量
在回调外将外层的this赋值给一个变量(比如that/self),回调内使用这个变量访问目标属性:
console.log(this.variableInQuestion); const that = this; this.arrayOfObjects.each(function(thing) { if (that.variableInQuestion !== undefined && thing.property == that.variableInQuestion) { // ... } });
3. 使用bind绑定this
通过Function.prototype.bind方法,将回调函数的this强制绑定为外层的this:
console.log(this.variableInQuestion); this.arrayOfObjects.each(function(thing) { if (this.variableInQuestion !== undefined && thing.property == this.variableInQuestion) { // ... } }.bind(this));
内容的提问来源于stack exchange,提问作者QuillAndSaber
相关产品推荐
相关产品推荐

