svelte icon indicating copy to clipboard operation
svelte copied to clipboard

onMount unmount callback does not fire off for nested if-block components

Open jkbz64 opened this issue 3 years ago • 3 comments

Describe the bug onMount unmount callback function does not fire off when used for in if-block nested component of unmounted parent (which is mounted in my case by svelte:component, didn't test it out using if-blocks).

Referring to the documentation when looking at onDestroy it says that it Schedules a callback to run immediately before the component is unmounted. but we cannot see unmount callback output anything (as run immediately before the component is unmounted implies unmount event) in the REPL logs.

Analyzing the output we can see that:

  • onDestroy callback is not followed by an unmount callback from onMount()
  • onDestroy callback is fired off even before mounting the component.
  • onMount unmount callback never fires off

The issue may be related to #5268 but the REPL doesn't even use transitions although I saw some transition code get generated in output JS.

To Reproduce https://svelte.dev/repl/9b9fca1b9c5049cbabaa47a71afb7212?version=3.38.2

Click Prepare then Detonate and look at the console

As we can see console outputs

"Inner1 mount"
"Before Inner1 unmount"
"Inner1 unmount"
"Inner2 mount"
"Inner2 unmount"
"Before Inner1 unmount"
"Inner1 mount"

Expected behavior The Inner1 component should fire off onMount -> onDestroy -> onUnmount (onMount returned function)

REPL should output probably in this case

"Inner1 mount"
"Before Inner1 unmount"
"Inner1 unmount"
"Inner2 mount"
"Inner2 unmount"
"Inner1 mount"
"Before Inner1 unmount"
"Inner1 ummount"

or in perfect world don't even mount Inner1 component on changing the parent component (the inner = 1 before _boom() is intended) but it probably is more of a feature request than bug report.

Workaround Use onDestroy with tick() instead of function returned from onMount

Severity The bug can be really dangerous if you are not aware of this behaviour - subscribing to events and not unsubscribing on unmount may lead to hard to detect problems. The issue can be workaround so it's not a showstopper.

jkbz64 avatar Jun 10 '21 02:06 jkbz64

Another workaround => REPL: https://svelte.dev/repl/8dcde41369cf440da948b65bc069322b?version=3.38.2

mdynnl avatar Jun 18 '21 08:06 mdynnl

Thank you @mdynnl . This was driving me insane.

Lucasmiguelmac avatar Aug 17 '22 02:08 Lucasmiguelmac

It seems it got partially fixed in svelte 3.51.0 - specifically (im guessing) #7860 but "before unmount" still is getting called before the component even mounts.

Here is the output

"Inner1 mount"
"Before Inner1 unmount"
"Inner1 unmount"
"Inner2 mount"
"Inner2 unmount"
> "Before unmount" is still before mount!
"Before Inner1 unmount"
"Inner1 mount"
> Before it did not output "unmount"
"Inner1 unmount"

EDIT: the bug still occurs in Svelte 4

jkbz64 avatar Jan 25 '23 08:01 jkbz64