承诺在Firefox调试器上返回后无法访问此上下文

时间:2020-11-02 09:46:00

标签: javascript typescript firefox

我想知道为什么我在调试器上看不到上下文“ this”对象。在firefox调试器上未定义,但在chrome调试器上显示。

我的ts文件的代码是:

export class MYClass {
refresData(): void {
this.myService.getFunction(1)
      .then(result => {
        this.myProperty = result; // This object appears as undefined
 }
}
}

服务代码:

async getFunction(id: number): Promise<MyObject> {
    return of({...}).toPromise();
  }

Windows 10上的版本82.0.2(64位)

1 个答案:

答案 0 :(得分:0)

如果在promise中定义新的回调,则无法访问子作用域中的父作用域,这意味着您找不到“ this.property”

我通过传递在父作用域中定义的回调函数来解决它,就像:

    export class MYClass {
    refresData(): void {
    this.myService.getFunction(1)
      .then(myCallback)
      }
    myCallback(result) {
      this.myProperty = result; // here you can do it
      }
    }