svelte: State is undefined in cleanup functions when component is recreated with `{#key}`

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

About this issue

  • Original URL
  • State: closed
  • Created 2 years ago
  • Comments: 16 (14 by maintainers)

Most upvoted comments

I found out there was a subtle bug that actually was the cause for this in the end, so I’ll put up a PR to address this issue. Thanks for bearing with me.

@trueadm personally I expect svelte here to behave like it inserts const value = value before teardown:

onMount(() => {
  intervalId = setInterval(() => {}, 1000)
  const intervalId = intervalId;
  console.log(intervalId);
  return () => {
    console.log(intervalId);
  }
});

onMount(() => {
  const intervalId = intervalId;
  console.log(intervalId);
  return () => {
    console.log(intervalId);
  }
});

So that if we do console.log(something) in both body of onMount and its teardown function it shows the same result. That was my expectation after that change in 5.23 at least. I feel like this is intuitive, but maybe I understood it wrongly.

I believe this should have been handled in 5.23.0: https://github.com/sveltejs/svelte/pull/15469, but probably this specific scenario was missed somehow.

@trueadm am I correct here?