没有.bind的FlowType没有对Mobx Flow函数进行类型检查(this)

Ada*_*lls 5 javascript eslint flowtype mobx mobx-react

当我们使用MobX流程修饰函数时,flowtype认为this是any类型并且没有类型检查.

class MyComponent extends Component<*> {
   actionMethod = flow(function*(){
        yield this.notAMethod();
   });
}
Run Code Online (Sandbox Code Playgroud)

但是,如果我们将它绑定到生成器,则flow会理解thisis 的类型MyComponent.

 class MyComponent extends Component<*> {
       actionMethod = flow((function*(){
            yield this.notAMethod();
       }).bind(this));
    }
Run Code Online (Sandbox Code Playgroud)

我的问题是我们如何确保对这些方法进行类型检查.

  • 是否有任何linting规则确保我们正确绑定(this)?
  • 我们可以改善mobx类型吗?
  • 这是流量的问题吗?

Nic*_*one 2

您的问题归结为创建自定义 lint 的能力。Eslint 有一个很棒的库,可以让您编写自己的 eslint 规则。您可以使用 来比较使用https://astexplorer.net/和不使用 的代码之间的差异this。然后你可以编写一个看起来像这样的 eslint 规则(未经测试):

// @no-flow
"use strict";
// Help from  https://astexplorer.net/
module.exports.rules = {
  "mobx-flow-requires-bind": context => ({
    CallExpression: function(node) {
      const ancestors = context.getAncestors();
      const parent = ancestors.length > 0 && ancestors[ancestors.length - 1];
      if (node.callee && node.callee.name === "flow") {
        if (node.arguments.length === 1) {
          const callee = node.arguments[0].callee;
          if (!(callee && callee.property && callee.property.name === "bind")) {
            context.report(node, "Calls to flow must be used with .bind");
          }
        }
      }
    }
  })
};
Run Code Online (Sandbox Code Playgroud)

您可以通过本教程将上述代码集成到您的存储库中。