0

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

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()类的构造函数中创建的,如下所示:

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

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

如果我定义actions为回调数组,就像这样runTask: this.runTask(),这些动作似乎会按应有的方式运行。据我的同事说,这样做是不好的做法。加载类后调用操作的正确方法是什么?

4

1 回答 1

0

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

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();
于 2019-10-22T13:53:00.960 回答