javascriptstatesveltereactivesvelte-5

$state object could not be cloned


After I switched to Svelte 5 syntax I am getting this error when I pass a reactive variable to a function

let details = $state({
  user: '',
  pass: ''
})

// ...
await login(details) // <- error

but works if I spread the state variable:

await login({ ...details })

Why is spreading needed in Svelte 5 but not 4, and why is it not mentioned in the migration guide?


Solution

  • State that wraps objects or arrays creates a Proxy, this allows Svelte to fire change signals for each property access individually (previously the entire object was invalidated). Proxies cannot be cloned and the spread operation removes the proxy.

    If you hand off your state to a third-party API, the recommended approach is to get a plain object via $state.snapshot.