Skip to content

Async closures with $state dependencies don't update properly #18082

@phi-bre

Description

@phi-bre

Describe the bug

I'm playing around with async closures (think of svelte 5 alternatives to stores) and am running into the following quirks as seen in the reproduction:

In previous versions of svelte (~5.43.1):

  • The derived value simply didn't always update properly and always used the previous stale value instead of waiting for the up to date value.

Latest version of svelte:

  • Stops and breaks any reactivity of the $state counter after a few clicks (not even updating the template that uses the counter variable directly)
  • After uncommenting the $inspect line it still logs the reactivity updates of count correctly but throws:
    Cannot read properties of null (reading 'activate')
    
    (might be an unrelated playground only issue)

Unrelated to versions, there are waterfall warnings that I don't think should apply in this case.


Intended behavior and what I'm trying to achieve:

Currently only synchronous classes or closures are possible to be used as svelte 4 store alternatives. I would like to do some async work inside of the closure before returning the first value while keeping things reactive with outside signals at the same time.

Due to how svelte async compiles $derived(await) with a $.save statement, I feel like it should(?) preserve the reactivity tracking across the await gap, but maybe that's just a wrong assumption on my part.

Same pattern would be helpful to move lots of $derived(await) from a +page.svelte to a reusable function inside a .svelte.ts module.

I understand that this way of using $derived(await) may just be not be in scope of intended uses, I'm just playing around with what feels possible in theory based on what the rune primitives provide.

Even just knowing if this is undefined behavior or just a bug, would be of great help, thanks in advance!


Reproduction

https://svelte.dev/playground/hello-world?version=5.55.2#H4sIAAAAAAAACo1RTWvcMBD9K4MIRCam3lzd3YXSS4895Bb3oJXHi6g8Y6SRN4vxfw-SHVpoDr2-9_Q-NIsiM6Jq1Q_0nuHGwfegsXeCfaVqNTiPUbWvi5L7lHUZUPXHq2_T9CXO6CVjFxPxM9wyCZJE1apjtMFNcu6oE48ClhMJnOAhihHUh-prR5kz8U4WhkRWHBP06M1dz8YnrGDJgk4CSgoEhDf4GXh0EXXAyH5GOJ0hory4ETmJ1lUGdm43qeH5cDhUJU7WTzOvKLqEAQBYpigwMOeuPQY3Y6_NzTjZu5Uhu18nm_xiwv_Jt4x90FY3Rz1lh78Kbq5lwL--pe7H9zUNPDiKE1rZo6BpIJHlcUQSEAYJ7nrFAN8NEQsEND1MgScM4jACD0DJe9CZcHSFR2PFzUbwsero2Py5Iy2lka5Ky-MliTABk_XO_j4t25ztzk8neF7L7QsZW1gKsWbH7eEZOlK1EnwT1UpIuP6qlRjnb4561Q7GR1zfAaeDwfm1AgAA

Logs

System Info

playground

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