`$state` write in `@attach` click handler triggers `$effect` flush before delegated `onclick` — handler silently skipped
Description
When using {@attach} to register a click listener via on(node, 'click') from svelte/events, writing to a $state variable inside the handler causes $effect to flush synchronously via a microtask checkpoint during event propagation. If the $effect sets node.disabled = true, this happens before the event bubbles to the document root where Svelte 5's delegated onclick handler lives — causing onclick to be silently skipped.
This is 100% reproducible, not intermittent.
Reproduction
<!-- App.svelte -->
<script>
import { throttle } from "./throttle.svelte.js";
let onclickCount = $state(0);
let attachCount = $state(0);
function onAttach() {
attachCount++;
}
function handleClick() {
onclickCount++;
console.log(`[onclick] fired #${onclickCount}`);
}
</script>
<button {@attach throttle(onAttach)} onclick={handleClick}>
<span>Click me</span>
</button>
<ul>
<li>onclick count: <strong>{onclickCount}</strong></li>
<li>@attach count: <strong>{attachCount}</strong></li>
<li>Missed: <strong>{attachCount - onclickCount}</strong></li>
</ul>// throttle.svelte.js
import { on } from "svelte/events";
export function throttle(callback, ms = 3000) {
return node => {
let throttled = $state(false);
const off = on(node, "click", () => {
console.log("[attach] on(node, click) fired");
callback();
throttled = true;
setTimeout(() => (throttled = false), ms);
});
$effect(() => {
if (throttled) {
console.log("[attach] $effect → node.disabled = true");
node.disabled = true;
return () => {
console.log("[attach] $effect cleanup → node.disabled = false");
node.disabled = false;
};
}
});
return () => off();
};
}Expected Behavior
onclick handler fires on every click. The @attach throttle disables the button after the current event is fully dispatched.
Actual Behavior
onclick is never called. The $effect setting node.disabled = true flushes during event propagation — before the event reaches the document root where Svelte 5's delegated onclick handler lives.
Root Cause (confirmed via Chrome DevTools debugging)
The event flow with console instrumentation
[debug-capture] button.disabled: false ← document capture phase
[throttle] on(node, click) fired ← @attach handler on button (target/bubble phase)
[throttle] $effect → disabled = true ← $effect flushes HERE via microtask checkpoint!
[debug-bubble] button.disabled: true ← document bubble phase — too late, already disabled
← Svelte's delegated onclick SKIPPED
[throttle] $effect cleanup ← later: setTimeout restores buttonWhy this happens
The mechanism is a browser-level microtask checkpoint between event listeners on different DOM nodes during event propagation:
- User clicks
<span>inside<button> - Event bubbles to
<button>→on(node, 'click')handler fires → writes$state(throttled = true)→ Svelte schedules$effectas a microtask - Browser performs microtask checkpoint (JS call stack empties between listeners on
<button>anddocument) → microtask runs →$effectflushes →node.disabled = true - Event continues bubbling to
document→ Svelte's delegatedonclickhandler checksevent.target→ finds button isdisabled→ skipsonclick
Key insight: queueMicrotask does NOT help
We tested wrapping the $state write in queueMicrotask():
on(node, "click", () => {
queueMicrotask(() => {
throttled = true; // still flushes before onclick!
});
});The microtask checkpoint between DOM nodes executes this callback before the event reaches document. Confirmed via console logs:
[throttle] raw addEventListener fired
[throttle] queueMicrotask callback → setting throttled = true ← runs BEFORE document bubble!
[throttle] $effect → disabled = true
[debug-bubble] button.disabled: true ← too lateWorkaround: setTimeout(0) works
Only a macrotask (setTimeout(0)) defers the $state write past the entire event dispatch:
- Use setTimeout(0) to delay writing $state to the macrotask
- Reason: During event bubbling, microtask checkpoints are triggered between listeners on different DOM nodes.
- Writing to $state directly or via queueMicrotask will cause $effect to flush synchronously.
- Set disabled = true before the event bubbles up to the document.
- This causes the onclick event delegated to the document in Svelte 5 to be skipped.
on(node, "click", () => {
setTimeout(() => {
throttled = true; // runs after all event listeners complete
}, 0);
});Console output confirms onclick fires:
[debug-capture] button.disabled: false
[throttle] click fired
[onclick] onCopy fired ← ✅ onclick fires!
[debug-bubble] button.disabled: false ← ✅ still enabled during bubble
[throttle] setTimeout(0) → throttled=true
[throttle] $effect → disabled = true ← correctly delayedAnalysis
| Approach | $state write timing |
$effect flush timing |
onclick fires? |
|---|---|---|---|
| Synchronous write | Immediate | Microtask checkpoint (between button→document) | No |
queueMicrotask |
Microtask | Same microtask checkpoint | No |
setTimeout(0) |
Next macrotask | After event dispatch | Yes |
The fundamental issue: Svelte 5's $effect scheduling (microtask-based) is incompatible with its own event delegation (document-level) when $state is written inside event handlers on child elements. The browser's microtask checkpoint between DOM nodes during event propagation creates a window where $effect flushes and mutates the DOM before the delegated handler processes the event.
Suggested Fixes
- Defer
$effectDOM mutations during active event dispatch — detect when an event is propagating and batch DOM-mutating effects until afterdispatchEventcompletes - Don't check
disabledin the delegated event handler — if the button was enabled when the event was originally dispatched (capture phase), honor the click regardless of subsequent mutations - Document the limitation — warn that
@attachhandlers should not write$statethat triggers$effectDOM mutations if those mutations can interfere with delegated event handlers
Environment
- Svelte 5 (runes mode)
@attachdirective withon()fromsvelte/events$state+$effectin.svelte.ts/.svelte.jsrunes module- Tested in Chrome (via Astro + Svelte integration,
client:only="svelte") - Confirmed with both
on()fromsvelte/eventsand rawaddEventListener— the issue is$state/$effectscheduling, not the event registration method
Source: sveltejs/svelte