Skip to content

Bug: initialTransition fails when invoke has systemId #5454

@kolaworld

Description

@kolaworld

XState version

XState version 5

Description

initialTransition is documented as a pure function that computes state transitions without side effects. However, when called on a machine that has an invoke with a systemId, it throws "Actor with system ID 'X' already exists" on the first call.

The same machine with invoke but without systemId works correctly.

Expected result

Per the pure transitions documentation:

Pure transition functions allow you to compute the next state and actions of a state machine without creating a live actor or executing any side effects.

initialTransition(machine) should return the initial snapshot without any side effects, regardless of whether invokes have systemId or not.

Actual result

Adding systemId to an invoke causes initialTransition to fail immediately.

Root Cause Analysis

Local stack trace shows:

at _set (raise-ad4f12ad.cjs.js:413:19)
at new Actor (raise-ad4f12ad.cjs.js:635:19)
at createActor (raise-ad4f12ad.cjs.js:1130:10)
at resolveSpawn (raise-ad4f12ad.cjs.js:1219:16)
at resolveAndExecuteActionsWithContext (raise-ad4f12ad.cjs.js:2323:56)
at resolveActionsAndContext (raise-ad4f12ad.cjs.js:2346:21)
at enterStates (raise-ad4f12ad.cjs.js:2140:20)
at microstep (raise-ad4f12ad.cjs.js:2082:15)
at getInitialSnapshot (StateMachine-f73271f9.cjs.js:444:48)
at initialTransition (xstate.cjs.js:337:30)

It appears that during initialTransition:

  1. The machine enters states and invokes actors
  2. When an invoke has systemId, the actor is registered in a system
  3. Something causes the state to be entered twice (or the actor to be registered twice)
  4. The second registration fails because the systemId already exists

Reproduction

https://stackblitz.com/edit/github-pnpxlm9l?file=src%2Fmain.ts

Additional context

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions