svelte: reactive variable using $state breaks when updated inside #await

Describe the bug

I’m trying to migrate a svelte 4 app to version 5 but it seems that updating a variable marked with $state inside an async function called by {#await fn()} breaks the component with no errors in console.

Reproduction

I created a simple playground as you can see there’s no output but if you remove $state('world') and replace it by 'world' using the “old way” it works image

Logs

No response

System Info

System:
    OS: Linux 6.11 Debian GNU/Linux 11 (bullseye) 11 (bullseye)
    CPU: (14) x64 Intel(R) Core(TM) Ultra 7 165U
    Memory: 16.04 GB / 30.05 GB
    Container: Yes
    Shell: 5.1.4 - /bin/bash
  Binaries:
    Node: 20.18.0 - /usr/local/bin/node
    Yarn: 1.22.22 - /usr/local/bin/yarn
    npm: 10.8.2 - /usr/local/bin/npm
    pnpm: 9.12.2 - /usr/local/share/npm-global/bin/pnpm
  npmPackages:
    svelte: ^5.0.5 => 5.0.5

Severity

blocking an upgrade

About this issue

  • Original URL
  • State: closed
  • Created 2 years ago
  • Comments: 20 (17 by maintainers)

Most upvoted comments

Also would not necessarily treat the #await expression the same as any other {interpolation}. I think it’s fairly common for existing code using #await to update state/local flags, partially because #await is rather trash otherwise (awaited data would only be available in a restricted scope within the template, not in <script> code).

I found the solution and it’s a small change to SvelteMap. PR incoming.

Oh that’s a typo sorry, you shouldn’t

I put up a PR to at least console.error the error if there’s no catch block in DEV. That should help surface the problem as to why nothing is rendered.

I think the general error here is that there is an error but it’s being swallowed because there’s no catch block. Maybe if the error comes from Svelte and there is no catch block, then we console.error the message in DEV?

As to altering the behaviour to allow mutations – that just won’t work. The expression of the catch block is a tracked context – like a derived. It’s tracked so that it can read things and react to them changing. It also doesn’t make a very good function to make async – and maybe we should document this more, as as soon as you await inside it, things aren’t going to be tracked either.

However, because the function is async, you can use that to avoid the mutation error too, because mutations outside of the reactive context are permitted, and obviously doing await means you come out of that context. So this works:

https://svelte.dev/playground/a82cf40707aa4b0e9525fb7257a154b1?version=5.0.5

If we were to allow mutations in this logic expression, but not others, it would add to the confusion. So I’m not sure of there being any simple path solution here.

It breaks silently, I would hardly call that “working as intended”.