首页 > 解决方案 > 在 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 位)

标签: javascripttypescriptfirefox

解决方案


如果你在 Promise 中定义了一个新的回调,你就不能在子作用域内访问父作用域,这意味着你找不到你的“this.property”

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

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

推荐阅读