Skip to content

state_unsafe_mutation when mutating unused $state wrapped in a $derived #16164

Closed
@danieldiekmeier

Description

@danieldiekmeier

Describe the bug

I'm getting this bug since v5.34.0.

When I'm in an $effect and mutate the field of a $state that was wrapped in a $derived, I get the state_unsafe_mutation error. This only happens if the field in question is not (immediately) used in the template.

This might be related to #16137, but I'm not sure, so I opened this new issue instead since I'm able to reproduce it (even in development).

Reproduction

https://svelte.dev/playground/b5e28844304848328368c595b616351d?version=5.34.3 (open the console to see the error)

Same code with v5.33.19 works: https://svelte.dev/playground/b5e28844304848328368c595b616351d?version=5.33.19

Logs

Error
Svelte error: state_unsafe_mutation
Updating state inside a derived or a template expression is forbidden. If the value should not be reactive, declare it without `$state`
https://svelte.dev/e/state_unsafe_mutation
    at state_unsafe_mutation (playground:output:257:18)
    at set (playground:output:971:4)
    at eval (playground:output:653:8)
    at with_parent (playground:output:435:17)
    at Object.set (playground:output:651:11)
    at $effect (playground:output:3258:27)
    at update_reaction (playground:output:2013:57)
    at update_effect (playground:output:2180:19)
    at flush_queued_effects (playground:output:2288:6)
    at flush_queued_root_effects (playground:output:2260:6)

System Info

System:
    OS: macOS 15.5
    CPU: (10) arm64 Apple M1 Max
    Memory: 7.89 GB / 64.00 GB
    Shell: 5.9 - /bin/zsh
  Binaries:
    Node: 22.16.0 - ~/.local/share/mise/installs/node/22.16.0/bin/node
    npm: 10.9.2 - ~/.local/share/mise/installs/node/22.16.0/bin/npm
    pnpm: 10.12.1 - ~/.local/share/mise/installs/node/22.16.0/bin/pnpm
  Browsers:
    Chrome: 137.0.7151.104
    Edge: 137.0.3296.68
    Safari: 18.5
    Safari Technology Preview: 18.4
  npmPackages:
    svelte: ^5.34.3 => 5.34.3

Severity

blocking an upgrade

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions