Skip to content

Reseting state during on mount will cause a race condition inside key/each block #16795

@ivenuss

Description

@ivenuss

Describe the bug

When resetting item state to undefined during onMount or immediately in $effect, then it will crash because the each or key block can no longer access the item.id even though it's inside if block.

It looks like race condition, since if I wait one tick inside the onMount and then reset the value to undefined then it works.

Reproduction

Playground: https://svelte.dev/playground/7d7b34facedb4e4594f7175aaf805f8a?version=5.39.2

<script>
  let item = $state({ id: '1' });

  $effect(() => {
    // Clear the item
    item = undefined;
  });
</script>

{#if item}
  <!-- Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'id') -->
  {#key item.id}
	  {item.id}
  {/key}
  {#each [item.id] as id}
    {id}
  {/each}
{/if}

System Info

Svelte: 5.39.2

Severity

blocking

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