类型错误:无法读取未定义的属性

Art*_*s J 0 typescript angular

在 Angular 12 中工作,当我尝试在另一个方法中调用一个方法时遇到错误。这是我正在处理的内容的抽象(在 TypeScript 中就像在 Angular 中一样)

export class SomeClass {

  testvariable

  onTaskCompleted(results) {
    if (!results) {
      return;
    } else {
      //The line below works
      console.log(results);
      //The line below throws and error
      this.drawSomething(results)
      //In fact any reference to something outside of this function throws an error
      this.testvariable = results
    }
  }

  //The unique thing about OnTaskCompleted is that it is also used as a callback handler by a 3rd party library which is throwing the error
  //It is called in another function like so.  It is producing the correct result in onTaskCompleted, but breaks when I do something like above
  this.something.onResults(this.onResults);

  drawSomething(results) {
    if (!results) {
      return;
    } else {
      //perform some work
    }
  }
}

}
Run Code Online (Sandbox Code Playgroud)

当我运行这个时,我得到一个 TypeError: Cannot readproperties of undefined. 如果我在类中定义的任何其他函数中包含 doSomethingElse 函数,我就没有问题并且它会按预期工作。唯一值得注意的是,我遇到此问题的函数 doSomething() 被外部库用作回调,每当我包含对“外部”内容的任何引用时,这似乎就是引发错误的原因doSomething 函数中的 doSomething。任何想法将不胜感激

Jou*_*usi 5

我遇到此问题的函数 doSomething() 用作回调

您很可能会像这样传递函数:

library.externalFunction(this.doSomething);
Run Code Online (Sandbox Code Playgroud)

这是一个问题,因为this参数被设置为调用者,即它将不再是类实例。如果doSomething()尝试访问 上的属性this,将会出错。

一种正确的写法是:

library.externalFunction(param => this.doSomething(param));
Run Code Online (Sandbox Code Playgroud)

箭头函数捕获this并表现得更像您期望的那样。

或者,可以显式绑定this该函数:

library.externalFunction(this.doSomething.bind(this));
Run Code Online (Sandbox Code Playgroud)

这里有很多答案解释了函数作用域,例如/sf/answers/1419563981/