在 javascript 中实现状态机,核心做法是定义一个包含所有合法状态的集合,并通过事件驱动的方式触发状态间的转换。通常使用对象映射表来管理状态转换逻辑,结合当前状态和输入事件查找目标状态,若存在则更新状态并执行对应动作,否则抛出错误或忽略。这种方式能确保状态流转的确定性和可预测性,避免非法状态的出现。

StateMachine类如何封装状态与事件处理
通过创建一个类来封装状态机的内部逻辑,可以将状态数据、转换规则和事件处理器集中管理。实例化该类时传入初始状态和配置好的转换表,对外暴露 emit() 方法供外部调用。每次调用 emit() 时,类内部会根据当前状态和传入的事件类型查询转换表,找到对应的目标状态和回调函数。如果找到匹配项,就更新内部状态变量并执行回调;如果没找到,则记录错误或不作处理。这种封装方式使得状态机的使用变得简单且安全,外部代码只需关心发送什么事件,无需关心内部状态的具体变化细节。

class StateMachine {
constructor(initialState, transitions) {
this.currentState = initialState;
this.transitions = transitions;
}
emit(event) {
const currentTransitions = this.transitions[this.currentState];
if (!currentTransitions) {
throw new Error(`No transitions defined for state: ${this.currentState}`);
}
const transition = currentTransitions[event];
if (!transition) {
console.warn(`No transition found for event '${event}' in state '${this.currentState}'`);
return this.currentState;
}
const nextState = transition.target;
if (transition.action) {
transition.action(this.currentState, nextState);
}
this.currentState = nextState;
return this.currentState;
}
getState() {
return this.currentState;
}
}
// 示例用法
const machine = new StateMachine('idle', {
idle: {
start: { target: 'running', action: () => console.log('Started') }
},
running: {
stop: { target: 'idle', action: () => console.log('Stopped') },
pause: { target: 'paused', action: () => console.log('Paused') }
},
paused: {
resume: { target: 'running', action: () => console.log('Resumed') },
stop: { target: 'idle', action: () => console.log('Stopped from paused') }
}
});
console.log(machine.getState()); // 'idle'
machine.emit('start'); // Logs: Started
console.log(machine.getState()); // 'running'
machine.emit('pause'); // Logs: Paused
console.log(machine.getState()); // 'paused'
machine.emit('stop'); // Logs: Stopped from paused
console.log(machine.getState()); // 'idle'如何处理状态转换中的异常与边界情况
在实际应用中,状态转换可能会遇到未定义的事件或非法的状态组合。为了保持系统的健壮性,需要在状态机内部加入异常处理机制。当查询转换表找不到对应的目标状态时,可以选择抛出异常以强制开发者修复逻辑,或者返回当前状态并记录警告日志以便调试。此外,还可以支持“守卫条件”(Guard Clauses),即在转换发生前检查某些前置条件是否满足,只有条件成立时才允许状态切换。例如,在网络请求场景中,只有在连接建立成功后才能发送数据,否则应拒绝转换到“发送中”状态。这种机制增加了状态机的灵活性,使其能够适应更复杂的业务逻辑需求。
一个基于源码的 OpenAI Agents SDK JavaScript 和 TypeScript 技术文档。涵盖了代理编排、工具、转接、追踪以及实际安装路径。
立即学习“Java免费学习笔记(深入)”;

class RobustStateMachine extends StateMachine {
emit(event) {
const currentTransitions = this.transitions[this.currentState];
if (!currentTransitions) {
throw new Error(`No transitions defined for state: ${this.currentState}`);
}
const transition = currentTransitions[event];
if (!transition) {
console.warn(`No transition found for event '${event}' in state '${this.currentState}'`);
return this.currentState;
}
// 检查守卫条件
if (transition.guard && !transition.guard()) {
console.warn(`Guard condition failed for event '${event}' in state '${this.currentState}'`);
return this.currentState;
}
const nextState = transition.target;
if (transition.action) {
transition.action(this.currentState, nextState);
}
this.currentState = nextState;
return this.currentState;
}
}
// 示例:带守卫条件的状态机
const robustMachine = new RobustStateMachine('disconnected', {
disconnected: {
connect: {
target: 'connected',
guard: () => true, // 假设总是可以连接
action: () => console.log('Connected')
}
},
connected: {
disconnect: {
target: 'disconnected',
action: () => console.log('Disconnected')
},
send: {
target: 'sending',
guard: () => Math.random() > 0.5, // 随机守卫条件
action: () => console.log('Sending data')
}
},
sending: {
complete: {
target: 'connected',
action: () => console.log('Send complete')
}
}
});
console.log(robustMachine.getState()); // 'disconnected'
robustMachine.emit('connect'); // Logs: Connected
console.log(robustMachine.getState()); // 'connected'
robustMachine.emit('send'); // 可能因守卫条件失败而无输出
console.log(robustMachine.getState()); // 仍为 'connected' 如果守卫失败
robustMachine.emit('disconnect'); // Logs: Disconnected
console.log(robustMachine.getState()); // 'disconnected'基于程序中某个输入、条件或结果的具体问题
在上述代码中,当调用 emit('send') 时,如果守卫条件 Math.random() > 0.5 返回 false,状态将不会发生变化。这是一个具体的边界情况,展示了如何在状态转换中加入动态条件判断。开发者可以通过调整守卫函数的逻辑来控制状态流转的可能性,从而实现更精细的控制。例如,可以基于用户权限、网络状态或其他运行时数据来决定是否允许状态转换。这种设计模式使得状态机不仅是一个简单的状态列表,而是一个具有智能决策能力的系统组件。

















