Skip to content

State is undefined in cleanup functions when component is recreated with {#key} #15606

@zeroberry

Description

@zeroberry

Describe the bug

State becomes undefined in component cleanup functions (both onMount return functions and onDestroy callbacks) when the component is recreated using a {#key} block.

Reproduction

// App.svelte
<script>
  import { onMount } from 'svelte'
  import Component from './Component.svelte'

  let key = $state(0)

  onMount(() => {
    key = 1
  })
</script>

{#key key}
  <Component />
{/key}
// Component.svelte
<script>
  import { onMount } from 'svelte'

  let intervalId = $state()

  onMount(() => {
    intervalId = setInterval(() => {}, 1000)

    return () => {
      if (intervalId === undefined) throw new Error('intervalId is undefined')
          // ^? undefined
      clearInterval(intervalId)
    }
  })
</script>

https://svelte.dev/playground/6cece48d922a425d9be411b8711036aa?version=5.25.3

Logs

System Info

unnecessary

Severity

annoyance

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions