无法在订阅回调中设置未定义的属性

Cannot set properties of undefined in Subscription callback

我有一个 observable,它 returns 一个我需要在函数中操作的值,所以我认为如果我只是将函数作为回调发送而不是创建一个新的匿名函数会更清晰。但是我进行了更改并开始收到此错误消息:Error: Cannot set properties of undefined (setting 'name').

STACKBLITZ DEMO

  ngOnInit(): void {
     this.updateName('First New Name!');

     of('Second New Name!')
     .pipe(delay(1500))
     // .subscribe(name => this.updateName(name)); // Works!
     .subscribe(this.updateName); // Doesn't work - Error: Cannot set properties of undefined (setting 'name')
  }

  updateName(name: string): void {
      this.name = name;
  }

它应该这样工作吗?为什么会这样?

updateName 切换为 lambda/arrow 函数。

updateName = (name: string) => {
  this.name = name;
}

Sample Demo on StackBlitz


根据 Arrow function expressions,箭头函数不拥有 this

Arrow functions establish "this" based on the scope the Arrow function is defined within.

因此,箭头函数的作用是

this is looked up in scope just like a normal variable.

来源:@Felix's answer on How to access the correct this inside a callback