跳转到内容

@Includes / @Excludes

状态守卫装饰器,限制方法在特定状态下可调用。

@Includes

function Includes(...states: string[]): MethodDecorator

只允许在 states 中包含当前状态时调用,否则抛出 FSMError

class Player extends FSM {
@Includes('playing')
pause() {
// 只有 playing 状态下才能调用
}
}

错误信息:

{className} {action} failed: current state {state} not in {states}

this.state.toString() 用于比较(因此中间态的 toString() 也会参与判断)。

@Excludes

function Excludes(...states: string[]): MethodDecorator

不允许在 states 中包含当前状态时调用。

class Player extends FSM {
@Excludes('disabled')
play() {
// 除了 disabled 状态都可以
}
}

多状态

@Includes('playing', 'buffering')
pause() {}
@Excludes('disabled', 'errored')
play() {}

与 @ChangeState 组合

可叠加使用,装饰器从下往上应用:

@Includes('idle') // 外层:先校验
@ChangeState('idle', 'done') // 内层:再迁移
async fetch() {}

通常单独使用即可,@ChangeState 本身已包含 from 校验。

参见