【问题标题】:Eslint rule no-invalid-this and fat arrow function in class类中的 Eslint 规则 no-invalid-this 和胖箭头函数
【发布时间】:2021-02-19 05:50:18
【问题描述】:

我有以下课程:

export class MyClass {
  private foos: Foo[];

  constructor(foos: Foo[]) {
    this.foos = foos;
  }

  getByA = (myA: Mya): Foo => {
    return this.foos.find(foo => foo.a === myA) ?? unknownFoo();
  };
}

不幸的是,在我的胖箭头函数中,我收到了关于无效this 的警告:

ESLint: Unexpected 'this'.(no-invalid-this)

我的 eslint 插件版本是4.15.1

除了禁用它之外,我还能做些什么来使此规则正常工作?

【问题讨论】:

    标签: typescript eslint arrow-functions typescript-eslint


    【解决方案1】:

    您收到此错误是因为当您创建箭头函数时,您正在创建一个可以在您的类的不同上下文中调用的对象。所以当getByA被执行时,它可能在this不存在或不同的上下文中。

    一种选择是bind箭头函数的上下文:

    getByA = (myA: Mya): Foo => {
        return this.find(foo => foo.a === myA) ?? unknownFoo();
    }.bind(this.foos);
    

    有关此错误的更多资源以及如何在正确的上下文中正确使用this 的示例,请查看here

    【讨论】:

    • 添加 .bind(this.foos) 产生:TS2391: Function implementation is missing or not immediately following the declaration. TS7010: 'bind', which lacks return-type annotation, implicitly has an 'any' return type.
    • 尝试仅绑定this 并将之前的this 替换为this.foos
    • with bind(this) 我得到 TS2391: Function implementation is missing or not immediately following the declaration. 它在 TypeScript 中对你有用吗?
    • 在箭头函数上调用 bind 不会做任何事情,this 绑定基于语法,例如父函数/类。
    • (() => console.log('hello', this)).bind('world')() 输出:hello Window {0: global, 1: global, window: …}(function () { console.log('hello', this) }).bind('world')() 输出:hello String {'world'}
    猜你喜欢
    • 2023-02-04
    • 2022-01-08
    • 1970-01-01
    • 2020-11-27
    • 1970-01-01
    • 2019-10-30
    • 2021-04-25
    • 1970-01-01
    • 2017-09-13
    相关资源
    最近更新 更多