如何在 MobX 中将装饰器 @action 转换为非装饰器动作

How to convert decorator @action to non-decorator action in MobX

我正在从我的 React Native 应用程序中删除装饰器(babel 有太多问题)并且我的操作不起作用(包含的函数不起作用 运行)。

我正在翻译 class 动作,例如

class MyStore {
  //...

  @action 
  myAction(param) {
    //...
  }
}

class MyStore {
  //...

  myAction(param) {
    action("Perform action with param", (param) => {
      //...
    })
  }
}

将 class @action 转换为非装饰器形式的正确方法是什么?

您可以将操作定义为

class MyStore {
  //...

  myAction = action(param => {
    //...
  });
}

或使用runInAction()

class MyStore {
  //...

  myAction(param) {
    runInAction(() => {
      //...
    })
  }
}

What's the correct way to convert a class @action to the non-decorator form?

装饰器在运行时评估函数调用,因此简单地手动调用它们将是最直接的事情。 @action是一个方法装饰器,方法装饰器在运行时接受以下参数:

  1. 实例方法的class原型(静态方法的构造函数)
  2. 方法名(属性键)
  3. 方法的属性描述符

考虑到这一点,您可以简单地执行以下操作:

class MyStore {
    myAction(param) {
        // ...
    }
}

// Apply the @action decorator manually:
action(MyStore.prototype, "myAction");

或:

action(MyStore.prototype, "myAction", Object.getOwnPropertyDescriptor(MyStore.prototype, "myAction"));

如果您在 class 声明之后立即执行此操作,结果应该与使用装饰器的结果完全相同,而无需使用装饰器语法。