‘运行时错误’
客户端错误(Client errors)
¥Client errors
async_derived_orphan
Cannot create a `$derived(...)` with an `await` expression outside of an effect tree在 Svelte 中,有两种响应类型 - $derived 和 $effect。派生类可以在任何地方创建,因为它们会延迟运行,并且如果没有引用它们,就可以是 垃圾收集。相比之下,Effect 的依赖发生变化时,会持续积极运行,直到被销毁。
¥In Svelte there are two types of reaction — $derived and $effect. Deriveds can be created anywhere, because they run lazily and can be garbage collected if nothing references them. Effects, by contrast, keep running eagerly whenever their dependencies change, until they are destroyed.
因此,effect 只能在其他 effect(或 效果根,例如首次挂载组件时创建的 effect)内部创建,以便 Svelte 知道何时销毁它们。
¥Because of this, effects can only be created inside other effects (or effect roots, such as the one that is created when you first mount a component) so that Svelte knows when to destroy them.
当派生函数包含 await 表达式时,会出现一些小技巧:由于等到读取 {await getPromise()} 后再调用 getPromise 为时已晚,因此我们使用 effect 来主动调用它,并在值可用时通知 Svelte。但由于我们使用了 effect,因此只能在另一个 effect 内部创建异步的派生类。
¥Some sleight of hand occurs when a derived contains an await expression: Since waiting until we read {await getPromise()} to call getPromise would be too late, we use an effect to instead call it proactively, notifying Svelte when the value is available. But since we’re using an effect, we can only create asynchronous deriveds inside another effect.
bind_invalid_checkbox_value
Using `bind:value` together with a checkbox input is not allowed. Use `bind:checked` insteadbind_invalid_export
Component %component% has an export named `%key%` that a consumer component is trying to access using `bind:%key%`, which is disallowed. Instead, use `bind:this` (e.g. `<%name% bind:this={component} />`) and then access the property on the bound component instance (e.g. `component.%key%`)bind_not_bindable
A component is attempting to bind to a non-bindable property `%key%` belonging to %component% (i.e. `<%name% bind:%key%={...}>`). To mark a property as bindable: `let { %key% = $bindable() } = $props()`component_api_changed
Calling `%method%` on a component instance (of %component%) is no longer valid in Svelte 5请参阅 迁移指南 了解更多信息。
¥See the migration guide for more information.
component_api_invalid_new
Attempted to instantiate %component% with `new %name%`, which is no longer valid in Svelte 5. If this component is not under your control, set the `compatibility.componentApi` compiler option to `4` to keep it working.请参阅 迁移指南 了解更多信息。
¥See the migration guide for more information.
derived_references_self
A derived value cannot reference itself recursivelyeach_key_duplicate
Keyed each block has duplicate key at indexes %a% and %b%Keyed each block has duplicate key `%value%` at indexes %a% and %b%effect_in_teardown
`%rune%` cannot be used inside an effect cleanup functioneffect_in_unowned_derived
Effect cannot be created inside a `$derived` value that was not itself created inside an effecteffect_orphan
`%rune%` can only be used inside an effect (e.g. during component initialisation)effect_pending_outside_reaction
`$effect.pending()` can only be called inside an effect or derivedeffect_update_depth_exceeded
Maximum update depth exceeded. This typically indicates that an effect reads and writes the same piece of state如果某个效果更新了它也依赖的某个状态,它将重新运行,可能形成循环:
¥If an effect updates some state that it also depends on, it will re-run, potentially in a loop:
let let count: numbercount = function $state<0>(initial: 0): 0 (+1 overload)
namespace $state
$state(0);
function $effect(fn: () => void | (() => void)): void
namespace $effect
Runs code when a component is mounted to the DOM, and then whenever its dependencies change, i.e. $state or $derived values.
The timing of the execution is after the DOM has been updated.
Example:
$effect(() => console.log('The count is now ' + count));
If you return a function from the effect, it will be called right before the effect is run again, or when the component is unmounted.
Does not run during server-side rendering.
$effect(() => {
// this both reads and writes `count`,
// so will run in an infinite loop
let count: numbercount += 1;
});(Svelte 会在浏览器标签页崩溃之前进行干预。)
¥(Svelte intervenes before this can crash your browser tab.)
这同样适用于数组突变,因为它们同时读取和写入数组:
¥The same applies to array mutations, since these both read and write to the array:
let let array: string[]array = function $state<string[]>(initial: string[]): string[] (+1 overload)
namespace $state
$state(['hello']);
function $effect(fn: () => void | (() => void)): void
namespace $effect
Runs code when a component is mounted to the DOM, and then whenever its dependencies change, i.e. $state or $derived values.
The timing of the execution is after the DOM has been updated.
Example:
$effect(() => console.log('The count is now ' + count));
If you return a function from the effect, it will be called right before the effect is run again, or when the component is unmounted.
Does not run during server-side rendering.
$effect(() => {
let array: string[]array.Array<string>.push(...items: string[]): numberAppends new elements to the end of an array, and returns the new length of the array.
push('goodbye');
});请注意,只要效果是 ‘settles’,它就可以重新运行:
¥Note that it’s fine for an effect to re-run itself as long as it ‘settles’:
function $effect(fn: () => void | (() => void)): void
namespace $effect
Runs code when a component is mounted to the DOM, and then whenever its dependencies change, i.e. $state or $derived values.
The timing of the execution is after the DOM has been updated.
Example:
$effect(() => console.log('The count is now ' + count));
If you return a function from the effect, it will be called right before the effect is run again, or when the component is unmounted.
Does not run during server-side rendering.
$effect(() => {
// this is okay, because sorting an already-sorted array
// won't result in a mutation
let array: string[]array.Array<string>.sort(compareFn?: ((a: string, b: string) => number) | undefined): string[]Sorts an array in place.
This method mutates the array and returns a reference to the same array.
sort();
});通常,遇到此问题时,所涉及的值不应该是状态(例如,如果你在效果中推送到 logs 数组,请将 logs 设置为普通数组而不是 $state([]))。在极少数情况下,你确实需要在效果(你应该避免的情况)中写入状态,你可以使用 untrack 读取状态,以避免将其添加为依赖。
¥Often when encountering this issue, the value in question shouldn’t be state (for example, if you are pushing to a logs array in an effect, make logs a normal array rather than $state([])). In the rare cases where you really do need to write to state in an effect — which you should avoid — you can read the state with untrack to avoid adding it as a dependency.
experimental_async_fork
Cannot use `fork(...)` unless the `experimental.async` compiler option is `true`flush_sync_in_effect
Cannot use `flushSync` inside an effectflushSync() 函数可用于同步刷新任何待处理的效果。如果效果当前正在刷新,则无法使用它 - 换句话说,你可以在状态更改后调用它,但不能在效果内部调用它。
¥The flushSync() function can be used to flush any pending effects synchronously. It cannot be used if effects are currently being flushed — in other words, you can call it after a state change but not inside an effect.
此限制仅适用于使用 experimental.async 选项的情况,该选项在 Svelte 6 中默认启用。
¥This restriction only applies when using the experimental.async option, which will be active by default in Svelte 6.
fork_discarded
Cannot commit a fork that was already discardedfork_timing
Cannot create a fork inside an effect or when state changes are pendingget_abort_signal_outside_reaction
`getAbortSignal()` can only be called inside an effect or derivedhydration_failed
Failed to hydrate the applicationinvalid_snippet
Could not `{@render}` snippet due to the expression being `null` or `undefined`. Consider using optional chaining `{@render snippet?.()}`lifecycle_legacy_only
`%name%(...)` cannot be used in runes modeprops_invalid_value
Cannot do `bind:%key%={undefined}` when `%key%` has a fallback valueprops_rest_readonly
Rest element properties of `$props()` such as `%property%` are readonlyrune_outside_svelte
The `%rune%` rune is only available inside `.svelte` and `.svelte.js/ts` filesset_context_after_init
`setContext` must be called when a component first initializes, not in a subsequent effect or after an `await` expression此限制仅适用于使用 experimental.async 选项的情况,该选项在 Svelte 6 中默认启用。
¥This restriction only applies when using the experimental.async option, which will be active by default in Svelte 6.
state_descriptors_fixed
Property descriptors defined on `$state` objects must contain `value` and always be `enumerable`, `configurable` and `writable`.state_prototype_fixed
Cannot set prototype of `$state` objectstate_unsafe_mutation
Updating state inside `$derived(...)`, `$inspect(...)` or a template expression is forbidden. If the value should not be reactive, declare it without `$state`当在评估 $derived 时更新状态时会发生此错误。你可能会在尝试一次 ‘derive’ 两个状态时遇到它:
¥This error occurs when state is updated while evaluating a $derived. You might encounter it while trying to ‘derive’ two pieces of state in one go:
<script>
let count = $state(0);
let even = $state(true);
let odd = $derived.by(() => {
even = count % 2 === 0;
return !even;
});
</script>
<button onclick={() => count++}>{count}</button>
<p>{count} is even: {even}</p>
<p>{count} is odd: {odd}</p>这是被禁止的,因为它会引入不稳定性:如果在重新计算 odd 之前更新 <p>{count} is even: {even}</p>,则 even 将过时。在大多数情况下,解决方案是使所有内容都派生:
¥This is forbidden because it introduces instability: if <p>{count} is even: {even}</p> is updated before odd is recalculated, even will be stale. In most cases the solution is to make everything derived:
let let even: booleaneven = function $derived<boolean>(expression: boolean): boolean
namespace $derived
Declares derived state, i.e. one that depends on other state variables.
The expression inside $derived(...) should be free of side-effects.
Example:
let double = $derived(count * 2);
$derived(let count: numbercount % 2 === 0);
let let odd: booleanodd = function $derived<boolean>(expression: boolean): boolean
namespace $derived
Declares derived state, i.e. one that depends on other state variables.
The expression inside $derived(...) should be free of side-effects.
Example:
let double = $derived(count * 2);
$derived(!let even: booleaneven);如果副作用不可避免,请改用 $effect。
¥If side-effects are unavoidable, use $effect instead.
svelte_boundary_reset_onerror
A `<svelte:boundary>` `reset` function cannot be called while an error is still being handled如果 <svelte:boundary> 包含 onerror 函数,则它不能同步调用提供的 reset 函数,因为边界仍然处于损坏状态。通常情况下,reset() 会在错误解决后稍后调用。
¥If a <svelte:boundary> has an onerror function, it must not call the provided reset function synchronously since the boundary is still in a broken state. Typically, reset() is called later, once the error has been resolved.
如果可以在 onerror 回调中解决错误,则必须至少等待边界稳定后再调用 reset(),例如使用 tick:
¥If it’s possible to resolve the error inside the onerror callback, you must at least wait for the boundary to settle before calling reset(), for example using tick:
<svelte:boundary onerror={async (error, reset) => {
fixTheError();
await tick();
reset();
}}>
</svelte:boundary>服务器错误(Server errors)
¥Server errors
await_invalid
Encountered asynchronous work while rendering synchronously.你(或你正在使用的框架)使用包含 await 表达式的组件调用了 render(...)。将 render 的结果作为 await,或者将 await(或包含它的组件)封装在带有 pending 代码片段的 <svelte:boundary> 中。
¥You (or the framework you’re using) called render(...) with a component containing an await expression. Either await the result of render or wrap the await (or the component containing it) in a <svelte:boundary> with a pending snippet.
html_deprecated
The `html` property of server render results has been deprecated. Use `body` instead.lifecycle_function_unavailable
`%name%(...)` is not available on the server某些方法(如 mount)在服务器上下文中运行时无法调用。避免预调用它们,即不在渲染期间调用。
¥Certain methods such as mount cannot be invoked while running in a server context. Avoid calling them eagerly, i.e. not during render.
共享错误(Shared errors)
¥Shared errors
invalid_default_snippet
Cannot use `{@render children(...)}` if the parent component uses `let:` directives. Consider using a named snippet instead此错误将在以下设置中抛出:
¥This error would be thrown in a setup like this:
<List {items} let:entry>
<span>{entry}</span>
</List><script>
let { items, children } = $props();
</script>
<ul>
{#each items as item}
<li>{@render children(item)}</li>
{/each}
</ul><script lang="ts">
let { items, children } = $props();
</script>
<ul>
{#each items as item}
<li>{@render children(item)}</li>
{/each}
</ul>这里,List.svelte 正在使用 {@render children(item),这意味着它期望 Parent.svelte 使用片段。相反,Parent.svelte 使用已弃用的 let: 指令。这种 API 组合不兼容,因此出现错误。
¥Here, List.svelte is using {@render children(item) which means it expects Parent.svelte to use snippets. Instead, Parent.svelte uses the deprecated let: directive. This combination of APIs is incompatible, hence the error.
invalid_snippet_arguments
A snippet function was passed invalid arguments. Snippets should only be instantiated via `{@render ...}`lifecycle_outside_component
`%name%(...)` can only be used during component initialisation某些生命周期方法只能在组件初始化期间使用。要修复此问题,请确保你在组件实例脚本的顶层内调用该方法。
¥Certain lifecycle methods can only be used during component initialisation. To fix this, make sure you’re invoking the method inside the top level of the instance script of your component.
<script>
import { onMount } from 'svelte';
function handleClick() {
// This is wrong
onMount(() => {})
}
// This is correct
onMount(() => {})
</script>
<button onclick={handleClick}>click me</button>missing_context
Context was not set in a parent componentcreateContext() 实用程序返回一对 [get, set] 函数。如果未使用 set 在父组件中设置上下文,get 将抛出错误。
¥The createContext() utility returns a [get, set] pair of functions. get will throw an error if set was not used to set the context in a parent component.
snippet_without_render_tag
Attempted to render a snippet without a `{@render}` block. This would cause the snippet code to be stringified instead of its content being rendered to the DOM. To fix this, change `{snippet}` to `{@render snippet()}`.抛出此错误的组件将如下所示(children 未被渲染):
¥A component throwing this error will look something like this (children is not being rendered):
<script>
let { children } = $props();
</script>
{children}...或者像这样(父组件传递了一个代码片段,而预期的是一个非代码片段值):
¥...or like this (a parent component is passing a snippet where a non-snippet value is expected):
<ChildComponent>
{#snippet label()}
<span>Hi!</span>
{/snippet}
</ChildComponent><script>
let { label } = $props();
</script>
<!-- This component doesn't expect a snippet, but the parent provided one -->
<p>{label}</p><script lang="ts">
let { label } = $props();
</script>
<!-- This component doesn't expect a snippet, but the parent provided one -->
<p>{label}</p>store_invalid_shape
`%name%` is not a store with a `subscribe` methodsvelte_element_invalid_this_value
The `this` prop on `<svelte:element>` must be a string, if defined