Skip to content

Commit 4ca9efa

Browse files
committed
docs: update state_unsafe_mutation message
1 parent 190c0c7 commit 4ca9efa

File tree

1 file changed

+20
-15
lines changed
  • packages/svelte/messages/client-errors

1 file changed

+20
-15
lines changed

packages/svelte/messages/client-errors/errors.md

Lines changed: 20 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -88,26 +88,31 @@ See the [migration guide](/docs/svelte/v5-migration-guide#Components-are-no-long
8888

8989
> Updating state inside a derived or a template expression is forbidden. If the value should not be reactive, declare it without `$state`
9090
91-
This error is thrown in a situation like this:
91+
This error occurs when state is updated while evaluating a `$derived`. You might encounter it while trying to 'derive' two pieces of state in one go:
9292

9393
```svelte
9494
<script>
95-
let count = $state(0);
96-
let multiple = $derived.by(() => {
97-
const result = count * 2;
98-
if (result > 10) {
99-
count = 0;
100-
}
101-
return result;
102-
});
95+
let count = $state(0);
96+
97+
let even = $state(true);
98+
99+
let odd = $derived.by(() => {
100+
if (count % 2 !== 0) even = false;
101+
return !even;
102+
});
103103
</script>
104104
105-
<button onclick={() => count++}>{count} / {multiple}</button>
105+
<button onclick={() => count++}>{count}</button>
106+
107+
<p>{count} is even: {even}</p>
108+
<p>{count} is odd: {odd}</p>
106109
```
107110

108-
Here, the `$derived` updates `count`, which is `$state` and therefore forbidden to do. It is forbidden because the reactive graph could become unstable as a result, leading to subtle bugs, like values being stale or effects firing in the wrong order. To prevent this, Svelte errors when detecting an update to a `$state` variable.
111+
This is forbidden because it introduces instability: if `<p>{count} is even: {even}</p>` is updated before `odd` is recalculated, `even` will be stale. In most cases the solution is to make everything derived:
112+
113+
```js
114+
let even = $derived(count % 2 === 0);
115+
let odd = $derived(!even);
116+
```
109117

110-
To fix this:
111-
- See if it's possible to refactor your `$derived` such that the update becomes unnecessary
112-
- Think about why you need to update `$state` inside a `$derived` in the first place. Maybe it's because you're using `bind:`, which leads you down a bad code path, and separating input and output path (by splitting it up to an attribute and an event, or by using [Function bindings](bind#Function-bindings)) makes it possible avoid the update
113-
- If it's unavoidable, you may need to use an [`$effect`]($effect) instead. This could include splitting parts of the `$derived` into an [`$effect`]($effect) which does the updates
118+
If side-effects are unavoidable, use [`$effect`]($effect) instead.

0 commit comments

Comments
 (0)