You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular中setTimeout调用服务出现Cannot read properties of undefined错误

问题原因

问题出在setTimeout回调的this上下文丢失。当你把this.doneTyping直接传给setTimeout时,这个方法的this不再指向你的Angular组件实例,而是变成了undefined(严格模式下),所以访问this.friendsListService和this.myInput都会触发Cannot read properties of undefined错误。

三种解决方案
  • 方案一:用箭头函数包裹回调调用
    修改newFunc中的setTimeout代码,通过箭头函数保留组件的this上下文:
newFunc() {
    clearTimeout(this.typingTimer);
    if (this.myInput) {
      this.typingTimer = setTimeout(() => this.doneTyping(), this.doneTypingInterval);
    }
}
  • 方案二:用bind绑定this到方法
    在传递doneTyping给setTimeout时,通过bind强制绑定组件实例的this:
newFunc() {
    clearTimeout(this.typingTimer);
    if (this.myInput) {
      this.typingTimer = setTimeout(this.doneTyping.bind(this), this.doneTypingInterval);
    }
}
  • 方案三:将doneTyping定义为箭头函数方法
    直接把doneTyping改成箭头函数形式,这样它的this会始终绑定组件实例:
doneTyping = () => {
    console.log("testing method" + this.myInput.value);
    let pattern = this.myInput.value;
    console.log(pattern);
    this.friendsListService.getUsernamesWithPattern(pattern).subscribe(data => {
      console.log(data);
    });
}

内容的提问来源于stack exchange,提问作者UltraLegend

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.15 03:44:53