【问题标题】:Cannot set properties of undefined in Subscription callback [duplicate]无法在订阅回调中设置未定义的属性 [重复]
【发布时间】:2021-10-24 05:07:04
【问题描述】:

我有一个 observable,它返回一个我需要在函数中操作的值,所以我认为如果我只是将函数作为回调发送而不是创建一个新的匿名函数会更简洁。但是我进行了更改,并开始收到此错误消息: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;
  }

它应该以这种方式工作吗?为什么会这样?

【问题讨论】:

    标签: angular typescript rxjs


    【解决方案1】:

    updateName 切换为 lambda/箭头函数。

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

    Sample Demo on StackBlitz


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

    箭头函数根据定义箭头函数的范围建立“this”。

    因此,箭头函数的作用是

    this 像普通变量一样在范围内查找。

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

    【讨论】:

    • 它有效,谢谢!您能否添加一些关于为什么会出现这种行为的解释或文档?
    猜你喜欢
    • 2018-07-22
    • 2021-12-15
    • 1970-01-01
    • 1970-01-01
    • 2020-03-07
    • 1970-01-01
    • 1970-01-01
    • 2017-05-09
    • 2020-09-14
    相关资源
    最近更新 更多