使用 JS 标签语法 ​​"$:" 没有 "Cannot access <obj> before initialization" 错误

Use JS label syntax "$:" without "Cannot access <obj> before initialization" error

我在我的 Svelte 应用程序中使用此代码:

<script>
  import { query } from '@urql/svelte'

  import { MY_QUERY } from 'queries'

  $: myQuery = query({
    query: MY_QUERY,
    variables: { id }
  })
</script>

{#if !$myQuery}
  Loading...
{:else}
  Oh WOW! {$myQuery.data}
{/if}

在 Sapper 中尝试相同的代码我得到这个错误:

Cannot access 'myQuery' before initialization.

如果我更改以下行

有效!

为什么?

因为这是 Sapper 代码,而且我没有看到任何其他明显的东西,我认为你 运行 愚弄了这个 this bug。错误只发生在服务器端(SSR),不是吗?

然后解决方法是提示编译器在正确的位置声明变量:

  let myQuery // <=== add this

  $: myQuery = query({
    query: MY_QUERY,
    variables: { id }
  })