Scripts2026年4月11日·1 分钟阅读

XState — State Machines & Statecharts for Complex Logic

XState is a library for creating, interpreting, and executing finite state machines and statecharts. Model complex application logic declaratively with first-class TypeScript, React/Vue/Svelte bindings, and visual editor (Stately).

SC
Script Depot · Community
快速使用

先拿来用,再决定要不要深挖

这里应该同时让用户和 Agent 知道第一步该复制什么、安装什么、落到哪里。

npm i xstate @xstate/react
import { setup } from "xstate";
import { useMachine } from "@xstate/react";

const toggleMachine = setup({}).createMachine({
  id: "toggle",
  initial: "inactive",
  states: {
    inactive: { on: { TOGGLE: "active" } },
    active: { on: { TOGGLE: "inactive" } },
  },
});

function Toggle() {
  const [state, send] = useMachine(toggleMachine);
  return (
    <button onClick={() => send({ type: "TOGGLE" })}>
      {state.value}
    </button>
  );
}
介绍

XState is a library for creating, interpreting, and executing finite state machines and statecharts. Built by David Khourshid and the Stately team, it brings rigorous state modeling (SCXML-inspired) to JavaScript with full TypeScript support and a visual editor.

What XState Does

  • Finite state machines — explicit states and transitions
  • Statecharts — hierarchical, parallel, history states
  • Actors — async, message-passing concurrency model
  • Visualizer — Stately Studio for drag-and-drop editing
  • Guards & actions — conditional transitions and side-effects
  • Delayed transitions — timeouts without setTimeout juggling
  • Model-based testing — auto-generate tests from machines

Architecture

A machine is a pure object describing states, events, transitions, and effects. createActor(machine) spawns a running instance. Actors can spawn child actors, creating a hierarchy. Works in any JS runtime; bindings exist for React, Vue, Svelte, Solid.

Self-Hosting

Client-side library. Stately Studio is a SaaS for visual editing (optional), but machines run anywhere.

Key Features

  • Statecharts with hierarchy & parallel states
  • Actor model for concurrency
  • Fully type-safe (v5 uses setup() for inference)
  • Visual editor (Stately Studio)
  • Test generator (@xstate/test)
  • Framework-agnostic core
  • Bindings for React, Vue, Svelte, Solid
  • SCXML export

Comparison

Library Paradigm Complexity Visual Tools
XState Statecharts Highest ceiling Stately Studio
Zustand Hooks store Low No
Redux Reducers Medium Redux DevTools
MobX Reactive Medium MobX DevTools

常见问题 FAQ

Q: 什么时候用 XState? A: 复杂 UI 流程(多步表单、付款流程、视频播放器、协作编辑)。简单全局状态用 Zustand 就够了。

Q: Actor 模型是什么? A: 并发模型:每个 actor 是独立状态机,通过消息通信。避免共享状态带来的竞态。

Q: v5 有什么变化? A: v5 引入 setup() API 实现更好的 TS 类型推断、简化 actor 系统、移除 interpret 改用 createActor。

来源与致谢 Sources

讨论

登录后参与讨论。
还没有评论,来写第一条吧。

相关资产