在 XState FMS 中调用操作的正确方法是什么?

What's the proper way to invoke actions in XState FMS?

我在文件task_statemachine.js中对XState FMS的定义如下:

module.exports = {
  id: 'runner',
  initial: 'setup',
  states: {
    setup: {
      on: {
        RECEIVED: {
          target: 'running',
          actions: 'runTask',
        },

        ERROR: {
          target: 'error',
          actions: 'taskError',
        },

        TERMINATED: {
          target: 'terminated',
          actions: 'terminate',
        },
      },
    },

    running: {
      on: {
        COMPLETE: {
          target: 'complete',
          actions: 'taskComplete',
        },

        ERROR: {
          target: 'error',
          actions: 'taskError',
        },

        TERMINATED: {
          target: 'terminated',
          actions: 'terminate',
        },
      },
    },

    terminated: {
      type: 'final',
    },

    complete: {
      type: 'final',
    },

    error: {
      type: 'final',
    },
  },
}

实际机器本身和服务是在 TASK() class 的构造函数中创建的,如下所示:

if (!this.state) this.state = interpret(Machine(require('./task_statemachine'), {
      actions: {
        runTask: this.runTask,
        taskComplete: this.taskComplete,
        taskError: this.taskError,
        terminate: this.terminate
      }
    })).start();

我在尝试 运行 应该调用 class 中定义的函数的操作时遇到问题。我通过以下方式发送事件 this.state.send('COMPLETE');

如果我将 actions 定义为回调数组,就像这样 runTask: this.runTask() 操作看起来 运行 是应该的。据我的同事说,这样做是一种不好的做法。加载 class 后调用操作的正确方法是什么?

问题是由 this 绑定引起的。解决方案是将函数回调变形为 actions 数组中的箭头函数。

if (!this.state) this.state = interpret(Machine(require('./task_statemachine'), {
      actions: {
        // High Level Functions
        runTask: () => {
          this.runTask()
        },
        taskComplete: () => {
          this.taskComplete()
        },
        taskError: () => {
          this.taskError()
        },
        terminate: () => {
          this.terminate()
        }

        // runTask() Functions
      }
    })).start();