`), and cannot be observed with a `ResizeObserver`. You will need to change the `display` style of these elements to something else, such as `inline-block`. Note that CSS transformations do not trigger `ResizeObserver` callbacks.
## bind:this
```svelte
bind:this={dom_node}
```
To get a reference to a DOM node, use `bind:this`. The value will be `undefined` until the component is mounted — in other words, you should read it inside an effect or an event handler, but not during component initialisation:
```svelte
```
Components also support `bind:this`, allowing you to interact with component instances programmatically.
```svelte
cart.empty()}> Empty shopping cart
```
```svelte
```
## bind:_property_ for components
```svelte
bind:property={variable}
```
You can bind to component props using the same syntax as for elements.
```svelte
```
While Svelte props are reactive without binding, that reactivity only flows downward into the component by default. Using `bind:property` allows changes to the property from within the component to flow back up out of the component.
To mark a property as bindable, use the [`$bindable`]($bindable) rune:
```svelte
```
Declaring a property as bindable means it _can_ be used using `bind:`, not that it _must_ be used using `bind:`.
Bindable properties can have a fallback value:
```svelte
```
This fallback value _only_ applies when the property is _not_ bound. When the property is bound and a fallback value is present, the parent is expected to provide a value other than `undefined`, else a runtime error is thrown. This prevents hard-to-reason-about situations where it's unclear which value should apply.
# use:
> [!NOTE]
> In Svelte 5.29 and newer, consider using [attachments](@attach) instead, as they are more flexible and composable.
Actions are functions that are called when an element is mounted. They are added with the `use:` directive, and will typically use an `$effect` so that they can reset any state when the element is unmounted:
```svelte
...
```
An action can be called with an argument:
```svelte
...
```
The action is only called once (but not during server-side rendering) — it will _not_ run again if the argument changes.
> [!LEGACY]
> Prior to the `$effect` rune, actions could return an object with `update` and `destroy` methods, where `update` would be called with the latest value of the argument if it changed. Using effects is preferred.
## Typing
The `Action` interface receives three optional type arguments — a node type (which can be `Element`, if the action applies to everything), a parameter, and any custom event handlers created by the action:
```svelte
...
```
# transition:
A _transition_ is triggered by an element entering or leaving the DOM as a result of a state change.
When a block (such as an `{#if ...}` block) is transitioning out, all elements inside it, including those that do not have their own transitions, are kept in the DOM until every transition in the block has been completed.
The `transition:` directive indicates a _bidirectional_ transition, which means it can be smoothly reversed while the transition is in progress.
```svelte
visible = !visible}>toggle
{#if visible}
fades in and out
{/if}
```
## Local vs global
Transitions are local by default. Local transitions only play when the block they belong to is created or destroyed, _not_ when parent blocks are created or destroyed.
```svelte
{#if x}
{#if y}
fades in and out only when y changes
fades in and out when x or y change
{/if}
{/if}
```
## Built-in transitions
A selection of built-in transitions can be imported from the [`svelte/transition`](svelte-transition) module.
## Transition parameters
Transitions can have parameters.
(The double `{{curlies}}` aren't a special syntax; this is an object literal inside an expression tag.)
```svelte
{#if visible}
fades in and out over two seconds
{/if}
```
## Custom transition functions
```js
/// copy: false
// @noErrors
transition = (node: HTMLElement, params: any, options: { direction: 'in' | 'out' | 'both' }) => {
delay?: number,
duration?: number,
easing?: (t: number) => number,
css?: (t: number, u: number) => string,
tick?: (t: number, u: number) => void
}
```
Transitions can use custom functions. If the returned object has a `css` function, Svelte will generate keyframes for a [web animation](https://developer.mozilla.org/en-US/docs/Web/API/Web_Animations_API).
The `t` argument passed to `css` is a value between `0` and `1` after the `easing` function has been applied. _In_ transitions run from `0` to `1`, _out_ transitions run from `1` to `0` — in other words, `1` is the element's natural state, as though no transition had been applied. The `u` argument is equal to `1 - t`.
The function is called repeatedly _before_ the transition begins, with different `t` and `u` arguments.
```svelte
{#if visible}
whooshes in
{/if}
```
A custom transition function can also return a `tick` function, which is called _during_ the transition with the same `t` and `u` arguments.
> [!NOTE] If it's possible to use `css` instead of `tick`, do so — web animations can run off the main thread, preventing jank on slower devices.
```svelte
{#if visible}
The quick brown fox jumps over the lazy dog
{/if}
```
If a transition returns a function instead of a transition object, the function will be called in the next microtask. This allows multiple transitions to coordinate, making [crossfade effects](/tutorial/deferred-transitions) possible.
Transition functions also receive a third argument, `options`, which contains information about the transition.
Available values in the `options` object are:
- `direction` - one of `in`, `out`, or `both` depending on the type of transition
## Transition events
An element with transitions will dispatch the following events in addition to any standard DOM events:
- `introstart`
- `introend`
- `outrostart`
- `outroend`
```svelte
{#if visible}
(status = 'intro started')}
onoutrostart={() => (status = 'outro started')}
onintroend={() => (status = 'intro ended')}
onoutroend={() => (status = 'outro ended')}
>
Flies in and out
{/if}
```
# in: and out:
The `in:` and `out:` directives are identical to [`transition:`](transition), except that the resulting transitions are not bidirectional — an `in` transition will continue to 'play' alongside the `out` transition, rather than reversing, if the block is outroed while the transition is in progress. If an out transition is aborted, transitions will restart from scratch.
```svelte
visible
{#if visible}
flies in, fades out
{/if}
```
# animate:
An animation is triggered when the contents of a [keyed each block](each#Keyed-each-blocks) are re-ordered. Animations do not run when an element is added or removed, only when the index of an existing data item within the each block changes. Animate directives must be on an element that is an _immediate_ child of a keyed each block.
Animations can be used with Svelte's [built-in animation functions](svelte-animate) or [custom animation functions](#Custom-animation-functions).
```svelte
{#each list as item, index (item)}
{item}
{/each}
```
## Animation Parameters
As with actions and transitions, animations can have parameters.
(The double `{{curlies}}` aren't a special syntax; this is an object literal inside an expression tag.)
```svelte
{#each list as item, index (item)}
{item}
{/each}
```
## Custom animation functions
```js
/// copy: false
// @noErrors
animation = (node: HTMLElement, { from: DOMRect, to: DOMRect } , params: any) => {
delay?: number,
duration?: number,
easing?: (t: number) => number,
css?: (t: number, u: number) => string,
tick?: (t: number, u: number) => void
}
```
Animations can use custom functions that provide the `node`, an `animation` object and any `parameters` as arguments. The `animation` parameter is an object containing `from` and `to` properties each containing a [DOMRect](https://developer.mozilla.org/en-US/docs/Web/API/DOMRect#Properties) describing the geometry of the element in its `start` and `end` positions. The `from` property is the DOMRect of the element in its starting position, and the `to` property is the DOMRect of the element in its final position after the list has been reordered and the DOM updated.
If the returned object has a `css` method, Svelte will create a [web animation](https://developer.mozilla.org/en-US/docs/Web/API/Web_Animations_API) that plays on the element.
The `t` argument passed to `css` is a value that goes from `0` and `1` after the `easing` function has been applied. The `u` argument is equal to `1 - t`.
The function is called repeatedly _before_ the animation begins, with different `t` and `u` arguments.
```svelte
{#each list as item, index (item)}
{item}
{/each}
```
A custom animation function can also return a `tick` function, which is called _during_ the animation with the same `t` and `u` arguments.
> [!NOTE] If it's possible to use `css` instead of `tick`, do so — web animations can run off the main thread, preventing jank on slower devices.
```svelte
{#each list as item, index (item)}
{item}
{/each}
```
# style:
The `style:` directive provides a shorthand for setting multiple styles on an element.
```svelte
...
...
```
The value can contain arbitrary expressions:
```svelte
...
```
The shorthand form is allowed:
```svelte
...
```
Multiple styles can be set on a single element:
```svelte
...
```
To mark a style as important, use the `|important` modifier:
```svelte
...
```
When `style:` directives are combined with `style` attributes, the directives will take precedence,
even over `!important` properties:
```svelte
This will be red
This will still be red
```
# class
有两种方式为元素设置类:元素的 `class` 属性,以及 `class:` 指令。
##
属性
原始值被当作任何其他属性来处理:
```svelte
...
```
> \[!注意\] 由于历史原因,假值(如`false`和`NaN`)会被转换为字符串(`class="false"`),尽管`class={undefined}`(或`null`)会导致属性完全省略。在 Svelte 的下一个版本中,所有假值都将导致`class`属性被省略。
###
对象和数组
自 Svelte 5.16 起,`class`可以是对象或数组,并使用[clsx](https://github.com/lukeed/clsx)转换为字符串。
如果值是对象,则添加真值键:
```svelte
...
```
如果值是数组,则将真值合并:
```svelte
...
```
请注意,无论是使用数组还是对象形式,我们都可以使用单个条件同时设置多个类,这在使用 Tailwind 等工具时尤其有用。
数组可以包含数组和对象,clsx 将它们扁平化。这对于将本地类与 props 结合很有用,例如:
```svelte
{@render props.children?.()}
```
该组件的用户可以使用对象、数组和字符串的混合:
```svelte
useTailwind = true}
class={{ 'bg-blue-700 sm:w-1/2': useTailwind }}
>
Accept the inevitability of Tailwind
```
Svelte 还暴露了 `ClassValue` 类型,这是元素上 `class` 属性接受的类型。如果您想在组件属性中使用类型安全的类名,这将很有用:
```svelte
...
```
## The `class:` directive
在 Svelte 5.16 之前,`class:`指令是设置元素条件类最方便的方式。
```svelte
...
...
```
与其它指令一样,当类名与值相同时,我们可以使用缩写:
```svelte
...
```
> \[注意\] 除非您正在使用较旧的 Svelte 版本,否则请考虑避免使用`class:`,因为该属性更强大且可组合。
# await
截至 Svelte 5.36,您可以在组件中三个之前不可用的位置使用`await`关键字:
* 在组件的最高级别中 `脚本`
* 内部 `$derived(...)` 声明
* 在您的标记内
此功能目前处于实验阶段,您必须通过添加 `experimental.async` 选项来启用,通常在您 [配置](/docs/kit/configuration) Svelte 时进行,通常在 `svelte.config.js` 中:
```js
/// file: svelte.config.js
export default {
compilerOptions: {
experimental: {
async: true
}
}
};
```
实验标志将在 Svelte 6 中移除。
##
边界
当前,您只能在具有 `await` 的 [``](svelte-boundary) 内部使用一个 `pending` 片段:
```svelte
{#snippet pending()}
loading...
{/snippet}
```
此限制将在 Svelte 支持异步服务器端渲染后解除(见[注意事项](#Caveats))。
> \[!注意\] 在[沙盒](/playground)中,您的应用在一个带有空挂起代码片段的边界内渲染,这样您就可以使用`await`而无需创建一个。
##
同步更新
當一個`await`表達式依賴於特定的狀態時,該狀態的變化將不會在 UI 中反應,直到異步操作完成,這樣 UI 就不會處於不一致的狀態。換句話說,在像[這個](/playground/untitled#H4sIAAAAAAAAE42QsWrDQBBEf2VZUkhYRE4gjSwJ0qVMkS6XYk9awcFpJe5Wdoy4fw-ycdykSPt2dpiZFYVGxgrf2PsJTlPwPWTcO-U-xwIH5zli9bminudNtwEsbl-v8_wYj-x1Y5Yi_8W7SZRFI1ZYxy64WVsjRj0rEDTwEJWUs6f8cKP2Tp8vVIxSPEsHwyKdukmA-j6jAmwO63Y1SidyCsIneA_T6CJn2ZBD00Jk_XAjT4tmQwEv-32eH6AsgYK6wXWOPPTs6Xy1CaxLECDYgb3kSUbq8p5aaifzorCt0RiUZbQcDIJ10ldH8gs3K6X2Xzqbro5zu1KCHaw2QQPrtclvwVSXc2sEC1T-Vqw0LJy-ClRy_uSkx2ogHzn9ADZ1CubKAQAA)...這樣的例子中。
```svelte
{a} + {b} = {await add(a, b)}
```
...如果您增加`a`,则``的内容将*不会*立即更新为读取此内容—
`2 + 2 = 3`
— 相反,当 `add(a, b)` 解析时,文本将更新为 `2 + 2 = 4`。
更新可以重叠——快速更新将在用户界面中反映出来,而较早的慢速更新仍在进行中。
##
并发
Svelte 会尽可能并行地执行异步操作。例如,如果你在标记中有两个`await`表达式...
```svelte
{await one()}
{await two()}
```
...两个函数将同时运行,因为它们是独立的表达式,尽管它们在视觉上是连续的。
这不适用于您代码中的 `await` 表达式,也不适用于 `
{#if error}
{
error = null;
reset();
}}>
oops! try again
{/if}
```
如果 `onerror` 函数内部发生错误(或者如果重新抛出错误),如果存在父边界,它将被处理。
#
```svelte
```
```svelte
```
The `` 元素允许您向 `window` 对象添加事件监听器,而无需担心在组件销毁时移除它们,或者在服务器端渲染时检查 `window` 的存在性。
此元素只能出现在组件的最顶层 — 它不能在块或元素内部。
```svelte
```
您也可以绑定以下属性:
* `innerWidth`
* `innerHeight`
* `outerWidth`
* `outerHeight`
* `scrollX`
* `scrollY`
* `在线` — 是 `window.navigator.onLine` 的别名
* `设备像素比`
所有除了 `scrollX` 和 `scrollY` 都是只读的。
```svelte
```
> \[注意\] 注意,页面不会滚动到初始值以避免可访问性问题。只有对`scrollX`和`scrollY`的绑定变量的后续更改将导致滚动。如果您在组件渲染时滚动有合法理由,请在`$effect`中调用`scrollTo()`。
#
```svelte
```
```svelte
```
与``类似,此元素允许您向`document`上的事件添加监听器,例如`visibilitychange`,这些事件在`window`上不会触发。它还允许您在`document`上使用[actions](use)。
与``一样,此元素只能出现在组件的最顶层,绝不能在块或元素内部。
```svelte
```
您也可以绑定以下属性:
* `activeElement`
* `fullscreenElement`
* `pointerLockElement`
* `可见状态`
所有都是只读的。
#
```svelte
```
与``类似,此元素允许您向`document.body`上的事件添加监听器,例如`mouseenter`和`mouseleave`,这些事件在`window`上不会触发。它还允许您在``元素上使用[actions](use)。
与``和``一样,此元素只能出现在组件的最顶层,绝不能在块或元素内部。
```svelte
```
#
```svelte
...
```
此元素使得将元素插入到 `document.head` 成为可能。在服务器端渲染期间,`head` 内容与主 `body` 内容分开暴露。
与``、``和``一样,此元素只能出现在组件的最顶层,绝不能在块或元素内部。
```svelte
Hello world!
```
#
```svelte
```
The `` 元素允许您渲染在作者时间未知的内容,例如因为它来自 CMS。任何存在的属性和事件监听器都将应用于该元素。
仅支持 `bind:this` 绑定,因为 Svelte 内置的绑定不支持泛型元素。
如果 `此` 具有空值,则不会渲染该元素及其子元素。
如果 `这` 是一个 [空元素](https://developer.mozilla.org/en-US/docs/Glossary/Void_element)(例如,`br`)并且 `` 有子元素,则在开发模式下将抛出运行时错误:
```svelte
This text cannot appear inside an hr element
```
Svelte 尽力从元素的周围推断正确的命名空间,但并不总是可行。您可以使用 `xmlns` 属性使其明确:
```svelte
```
`此`需要是一个有效的 DOM 元素标签,类似于`文本`或`Svelte:head`的标签将无法使用。
#
```svelte
```
The `` 元素提供了一个指定每个组件编译器选项的位置,这些选项在 [编译器部分](svelte-compiler#compile) 中有详细说明。可能的选项有:
* `runes={true}` — 强制组件进入 *符文模式*(见 [旧版 API](legacy-overview) 部分)
* `runes={false}` — 强制组件进入 *旧模式*
* `namespace="..."` — 该组件将使用的命名空间,可以是“html”(默认值)、“svg”或“mathml”
* `customElement={...}` — 使用此组件作为自定义元素时的 [选项](custom-elements#Component-options)。如果传递了一个字符串,则将其用作 `标签` 选项。
* `css="注入的"` — 组件将内联注入其样式:在服务器端渲染期间,它作为 `
```
### custom\_element\_props\_identifier
```
Using a rest element or a non-destructured declaration with `$props()` means that Svelte can't infer what properties to expose when creating a custom element. Consider destructuring all the props or explicitly specifying the `customElement.props` option.
```
### element\_implicitly\_closed
```
This element is implicitly closed by the following `%tag%`, which can cause an unexpected DOM structure. Add an explicit `%closing%` to avoid surprises.
```
In HTML, some elements are implicitly closed by another element. For example, you cannot nest a `` inside another `
`:
```html
hello
hello
```
Similarly, a parent element's closing tag will implicitly close all child elements, even if the `` was a typo and you meant to create a *new* element. To avoid ambiguity, it's always a good idea to have an explicit closing tag.
### element\_invalid\_self\_closing\_tag
```
Self-closing HTML tags for non-void elements are ambiguous — use `<%name% ...>%name%>` rather than `<%name% ... />`
```
In HTML, there's [no such thing as a self-closing tag](https://jakearchibald.com/2023/against-self-closing-tags-in-html/). While this *looks* like a self-contained element with some text next to it...
```html
some text!
```
...a spec-compliant HTML parser (such as a browser) will in fact parse it like this, with the text *inside* the icon:
```html
some text!
```
Some templating languages (including Svelte) will 'fix' HTML by turning ` ` into ` `. Others adhere to the spec. Both result in ambiguity and confusion when copy-pasting code between different contexts, and as such Svelte prompts you to resolve the ambiguity directly by having an explicit closing tag.
To automate this, run the dedicated migration:
```bash
npx sv migrate self-closing-tags
```
In a future version of Svelte, self-closing tags may be upgraded from a warning to an error.
### event\_directive\_deprecated
```
Using `on:%name%` to listen to the %name% event is deprecated. Use the event attribute `on%name%` instead
```
See [the migration guide](v5-migration-guide#Event-changes) for more info.
### export\_let\_unused
```
Component has unused export property '%name%'. If it is for external reference only, please consider using `export const %name%`
```
### legacy\_code
```
`%code%` is no longer valid — please use `%suggestion%` instead
```
### legacy\_component\_creation
```
Svelte 5 components are no longer classes. Instantiate them using `mount` or `hydrate` (imported from 'svelte') instead.
```
See the [migration guide](v5-migration-guide#Components-are-no-longer-classes) for more info.
### node\_invalid\_placement\_ssr
```
%message%. When rendering this component on the server, the resulting HTML will be modified by the browser (by moving, removing, or inserting elements), likely resulting in a `hydration_mismatch` warning
```
HTML restricts where certain elements can appear. In case of a violation the browser will 'repair' the HTML in a way that breaks Svelte's assumptions about the structure of your components. Some examples:
* `hello
world
` will result in `hello
world
` (the `` autoclosed the `
` because `
` cannot contain block-level elements)
* `option a
` will result in `option a ` (the `
` is removed)
* `
` will result in `
` (a `
` is auto-inserted)
This code will work when the component is rendered on the client (which is why this is a warning rather than an error), but if you use server rendering it will cause hydration to fail.
### non\_reactive\_update
```
`%name%` is updated, but is not declared with `$state(...)`. Changing its value will not correctly trigger updates
```
This warning is thrown when the compiler detects the following:
* a variable was declared without `$state` or `$state.raw`
* the variable is reassigned
* the variable is read in a reactive context
In this case, changing the value will not correctly trigger updates. Example:
```svelte
This value updates: {reactive}
This value does not update: {stale}
{
stale = 'updated';
reactive = 'updated';
}}>update
```
To fix this, wrap your variable declaration with `$state`.
### options\_deprecated\_accessors
```
The `accessors` option has been deprecated. It will have no effect in runes mode
```
### options\_deprecated\_immutable
```
The `immutable` option has been deprecated. It will have no effect in runes mode
```
### options\_missing\_custom\_element
```
The `customElement` option is used when generating a custom element. Did you forget the `customElement: true` compile option?
```
### options\_removed\_enable\_sourcemap
```
The `enableSourcemap` option has been removed. Source maps are always generated now, and tooling can choose to ignore them
```
### options\_removed\_hydratable
```
The `hydratable` option has been removed. Svelte components are always hydratable now
```
### options\_removed\_loop\_guard\_timeout
```
The `loopGuardTimeout` option has been removed
```
### options\_renamed\_ssr\_dom
```
`generate: "dom"` and `generate: "ssr"` options have been renamed to "client" and "server" respectively
```
### perf\_avoid\_inline\_class
```
Avoid 'new class' — instead, declare the class at the top level scope
```
### perf\_avoid\_nested\_class
```
Avoid declaring classes below the top level scope
```
### reactive\_declaration\_invalid\_placement
```
Reactive declarations only exist at the top level of the instance script
```
### reactive\_declaration\_module\_script\_dependency
```
Reassignments of module-level declarations will not cause reactive statements to update
```
### script\_context\_deprecated
```
`context="module"` is deprecated, use the `module` attribute instead
```
```svelte
```
### script\_unknown\_attribute
```
Unrecognized attribute — should be one of `generics`, `lang` or `module`. If this exists for a preprocessor, ensure that the preprocessor removes it
```
### slot\_element\_deprecated
```
Using `` to render parent content is deprecated. Use `{@render ...}` tags instead
```
See [the migration guide](v5-migration-guide#Snippets-instead-of-slots) for more info.
### state\_referenced\_locally
```
This reference only captures the initial value of `%name%`. Did you mean to reference it inside a %type% instead?
```
This warning is thrown when the compiler detects the following:
* A reactive variable is declared
* ...and later reassigned...
* ...and referenced in the same scope
This 'breaks the link' to the original state declaration. For example, if you pass the state to a function, the function loses access to the state once it is reassigned:
```svelte
count++}>
increment
```
```svelte
The count is {count}
```
To fix this, reference the variable such that it is lazily evaluated. For the above example, this can be achieved by wrapping `count` in a function:
```svelte
count++}>
increment
```
```svelte
The count is {+++count()+++}
```
For more info, see [Passing state into functions]($state#Passing-state-into-functions).
### store\_rune\_conflict
```
It looks like you're using the `$%name%` rune, but there is a local binding called `%name%`. Referencing a local variable with a `$` prefix will create a store subscription. Please rename `%name%` to avoid the ambiguity
```
### svelte\_component\_deprecated
```
`` is deprecated in runes mode — components are dynamic by default
```
In previous versions of Svelte, the component constructor was fixed when the component was rendered. In other words, if you wanted `` to re-render when `X` changed, you would either have to use `` or put the component inside a `{#key X}...{/key}` block.
In Svelte 5 this is no longer true — if `X` changes, `` re-renders.
In some cases `` syntax can be used as a replacement; a lowercased variable with property access is recognized as a component in Svelte 5.
For complex component resolution logic, an intermediary, capitalized variable may be necessary. E.g. in places where `@const` can be used:
```svelte
{#each items as item}
--- ---
+++{@const Component = item.condition ? Y : Z}+++
+++ +++
{/each}
```
A derived value may be used in other contexts:
```svelte
--- ---
+++ +++
```
### svelte\_element\_invalid\_this
```
`this` should be an `{expression}`. Using a string attribute value will cause an error in future versions of Svelte
```
### svelte\_self\_deprecated
```
`` is deprecated — use self-imports (e.g. `import %name% from './%basename%'`) instead
```
See [the note in the docs](legacy-svelte-self) for more info.
### unknown\_code
```
`%code%` is not a recognised code
```
```
`%code%` is not a recognised code (did you mean `%suggestion%`?)
```
# Runtime errors
## Client errors
### async\_derived\_orphan
```
Cannot create a `$derived(...)` with an `await` expression outside of an effect tree
```
In Svelte there are two types of reaction — [`$derived`](/docs/svelte/$derived) and [`$effect`](/docs/svelte/$effect). Deriveds can be created anywhere, because they run *lazily* and can be [garbage collected](https://developer.mozilla.org/en-US/docs/Glossary/Garbage_collection) if nothing references them. Effects, by contrast, keep running eagerly whenever their dependencies change, until they are destroyed.
Because of this, effects can only be created inside other effects (or [effect roots](/docs/svelte/$effect#$effect.root), such as the one that is created when you first mount a component) so that Svelte knows when to destroy them.
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` instead
```
### bind\_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](/docs/svelte/v5-migration-guide#Components-are-no-longer-classes) 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](/docs/svelte/v5-migration-guide#Components-are-no-longer-classes) for more information.
### derived\_references\_self
```
A derived value cannot reference itself recursively
```
### each\_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 function
```
### effect\_in\_unowned\_derived
```
Effect cannot be created inside a `$derived` value that was not itself created inside an effect
```
### effect\_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 derived
```
### effect\_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:
```js
let count = $state(0);
$effect(() => {
// this both reads and writes `count`,
// so will run in an infinite loop
count += 1;
});
```
(Svelte intervenes before this can crash your browser tab.)
The same applies to array mutations, since these both read and write to the array:
```js
let array = $state(['hello']);
$effect(() => {
array.push('goodbye');
});
```
Note that it's fine for an effect to re-run itself as long as it 'settles':
```js
let array = ['a', 'b', 'c'];
// ---cut---
$effect(() => {
// this is okay, because sorting an already-sorted array
// won't result in a mutation
array.sort();
});
```
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]($effect#When-not-to-use-$effect) — you can read the state with [untrack](svelte#untrack) to avoid adding it as a dependency.
### flush\_sync\_in\_effect
```
Cannot use `flushSync` inside an effect
```
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.
This restriction only applies when using the `experimental.async` option, which will be active by default in Svelte 6.
### get\_abort\_signal\_outside\_reaction
```
`getAbortSignal()` can only be called inside an effect or derived
```
### hydration\_failed
```
Failed to hydrate the application
```
### invalid\_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 mode
```
### props\_invalid\_value
```
Cannot do `bind:%key%={undefined}` when `%key%` has a fallback value
```
### props\_rest\_readonly
```
Rest element properties of `$props()` such as `%property%` are readonly
```
### rune\_outside\_svelte
```
The `%rune%` rune is only available inside `.svelte` and `.svelte.js/ts` files
```
### set\_context\_after\_init
```
`setContext` must be called when a component first initializes, not in a subsequent effect or after an `await` expression
```
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` object
```
### state\_unsafe\_mutation
```
Updating state inside `$derived(...)`, `$inspect(...)` or a template expression is forbidden. If the value should not be reactive, declare it without `$state`
```
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:
```svelte
count++}>{count}
{count} is even: {even}
{count} is odd: {odd}
```
This is forbidden because it introduces instability: if `{count} is even: {even}
` is updated before `odd` is recalculated, `even` will be stale. In most cases the solution is to make everything derived:
```js
let count = 0;
// ---cut---
let even = $derived(count % 2 === 0);
let odd = $derived(!even);
```
If side-effects are unavoidable, use [`$effect`]($effect) instead.
### svelte\_boundary\_reset\_onerror
```
A `` `reset` function cannot be called while an error is still being handled
```
If a [``](https://svelte.dev/docs/svelte/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.
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`](https://svelte.dev/docs/svelte/lifecycle-hooks#tick):
```svelte
{
fixTheError();
+++await tick();+++
reset();
}}>
```
## Server errors
### lifecycle\_function\_unavailable
```
`%name%(...)` is not available on the server
```
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
### await\_outside\_boundary
```
Cannot await outside a `` with a `pending` snippet
```
The `await` keyword can only appear in a `$derived(...)` or template expression, or at the top level of a component's `
{#each items as item}
{@render children(item)}
{/each}
```
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.
```svelte
click me
```
### 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()}`.
```
A component throwing this error will look something like this (`children` is not being rendered):
```svelte
{children}
```
...or like this (a parent component is passing a snippet where a non-snippet value is expected):
```svelte
{#snippet label()}
Hi!
{/snippet}
```
```svelte
{label}
```
### store\_invalid\_shape
```
`%name%` is not a store with a `subscribe` method
```
### svelte\_element\_invalid\_this\_value
```
The `this` prop on `` must be a string, if defined
```
# Runtime warnings
##
客户警告
### assignment\_value\_stale
```
Assignment to `%property%` property (%location%) will evaluate to the right-hand side, not the value of `%property%` following the assignment. This may result in unexpected behaviour.
```
给定一个这样的案例...
```svelte
add
items: {JSON.stringify(object.items)}
```
...當按鈕第一次被點擊時,推送到的數組是作業右側的 `[]`,但 `object.array` 的結果是一個空狀態代理。因此,推送的值將被丟棄。
您可以通过将其分为两个语句来修复此问题:
```js
let object = { array: [0] };
// ---cut---
function add() {
object.array ??= [];
object.array.push(object.array.length);
}
```
### await\_reactivity\_loss
```
Detected reactivity loss when reading `%name%`. This happens when state is read in an async function after an earlier `await`
```
Svelte 的基于信号的响应性是通过跟踪模板或`$derived(...)`表达式执行时读取哪些状态位来工作的。如果一个表达式包含一个`await`,Svelte 会将其转换,以便跟踪`await`之后的任何状态*之后*——换句话说,在这种情况下……
```js
let a = Promise.resolve(1);
let b = 2;
// ---cut---
let total = $derived(await a + b);
```
...两个`a`和`b`都被跟踪,即使`b`只在`a`解决后读取一次,在初始执行之后。
这并不适用于表达式内部不可见的 *await*。在这种情况下...
```js
let a = Promise.resolve(1);
let b = 2;
// ---cut---
async function sum() {
return await a + b;
}
let total = $derived(await sum());
```
...`total` 将取决于 `a`(立即读取)但不取决于 `b`(不读取)。解决方案是将值传递给函数:
```js
let a = Promise.resolve(1);
let b = 2;
// ---cut---
/**
* @param {Promise} a
* @param {number} b
*/
async function sum(a, b) {
return await a + b;
}
let total = $derived(await sum(a, b));
```
### await\_waterfall
```
An async derived, `%name%` (%location%) was not read immediately after it resolved. This often indicates an unnecessary waterfall, which can slow down your app
```
在这种情况下...
```js
async function one() { return 1 }
async function two() { return 2 }
// ---cut---
let a = $derived(await one());
let b = $derived(await two());
```
...第二个`$derived`将在第一个解决后创建。由于`await two()`不依赖于`a`的值,这种延迟,通常描述为“瀑布”,是不必要的。
(请注意,如果 `await one()` 和 `await two()` 的值随后更改,它们可以同时更改——瀑布效应仅在派生值首次创建时发生。)
您可以通过先创建承诺并在 *之后* 等待它们来解决此问题:
```js
async function one() { return 1 }
async function two() { return 2 }
// ---cut---
let aPromise = $derived(one());
let bPromise = $derived(two());
let a = $derived(await aPromise);
let b = $derived(await bPromise);
```
###
绑定属性非响应式
```
`%binding%` is binding to a non-reactive property
```
```
`%binding%` (%location%) is binding to a non-reactive property
```
###
控制台日志状态
```
Your `console.%method%` contained `$state` proxies. Consider using `$inspect(...)` or `$state.snapshot(...)` instead
```
当记录一个 [代理](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy) 时,浏览器开发者工具将记录代理本身而不是它所代表的值。在 Svelte 的情况下,`$state` 代理的 'target' 可能与其当前值不相似,这可能会造成困惑。
最简单的方法记录值随时间变化的情况是使用 [`$inspect`](/docs/svelte/$inspect) 符文。或者,为了一次性记录某些内容(例如,在事件处理器内部),可以使用 [`$state.snapshot`](/docs/svelte/$state#$state.snapshot) 来获取当前值的快照。
###
事件处理程序无效
```
%handler% should be a function. Did you mean to %suggestion%?
```
###
水合属性已更改
```
The `%attribute%` attribute on `%html%` changed its value between server and client renders. The client value, `%value%`, will be ignored in favour of the server value
```
某些属性,如`src`在` `元素上,在激活过程中不会被修复,即服务器值将被保留。这是因为更新这些属性可能会导致图像被重新获取(或者在`