Skip to content

Binding activeElement + removing focused element from DOM gives error #15742

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
RWDavid opened this issue Apr 11, 2025 · 1 comment
Open

Binding activeElement + removing focused element from DOM gives error #15742

RWDavid opened this issue Apr 11, 2025 · 1 comment

Comments

@RWDavid
Copy link

RWDavid commented Apr 11, 2025

Describe the bug

I can bind to the document's active element via <svelte:document bind:activeElement />.

However, this generates a state_unsafe_mutation error when I click an element and remove it from the DOM tree.

Reproduction

REPL

<script>
	let activeElement = $state();
	let showButton = $state(true);
</script>

<svelte:document bind:activeElement />
{#if showButton}
	<button onclick={() => showButton = false}>hello</button>
{/if}

Logs

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

System Info

REPL version=5.25.9

Severity

annoyance

@rkhatta1
Copy link

The update to activeElement is a consequence of the focus event, which happened just before the onclick handler ran. Svelte sees this as a state mutation happening reactively within the update process triggered by the onclick, hence the "unsafe mutation" error.

It definitely could be resolved; however, it is a stretch to make changes to the runtime interactions. Here's a workaround if you've not already found one :)

I could be way off here and please correct me if that's the case. Cheers!

dummdidumm added a commit that referenced this issue Apr 22, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants