You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
unlisten throws and leaks the listener when called before the registration eval lands (listeners[eventId] undefined) #15799
listen() resolves as soon as Rust answers the plugin:event|listen invoke, but the webview-side registry entry is written by a separate eval (listen_js_script). Calling the returned unlisten function inside that window crashes:
TypeError: undefined is not an object (evaluating 'listeners[eventId].handlerId')
The generated unlisten script guards the per-event object but not the entry itself (unlisten_js_script, crates/tauri/src/event/mod.rs):
— in contrast with event delivery (event_initialization_script in the same file), which does guard the entry: const listener = listeners[id]; if (listener) { … }.
The consequence is worse than the crash itself: the throw happens on the first line of _unlisten in @tauri-apps/api/event, so the invoke('plugin:event|unlisten', …) on its second line never runs. The backend listener stays registered and the JS callback stays alive — the "removed" handler keeps firing once the registration eval lands, and after a remount the event is handled twice. With React StrictMode (mount → unmount → mount in dev) this window is hit on essentially every fast unsubscribe; we saw it as a steady stream of unhandled rejections in Sentry plus double-delivered events.
Reproduction steps
import{listen}from"@tauri-apps/api/event"// Unlisten immediately after listen() resolves — before the registration// eval reaches the webview:constun=awaitlisten("my-evt",console.log)un()// → TypeError above + the backend listener is leaked
Any React StrictMode effect that subscribes on mount and unsubscribes in cleanup reproduces this via the dev-mode mount→unmount→mount cycle.
Expected behavior
Unlisten tolerates a not-yet-registered (or already-gone) entry: guard the lookup (listeners[eventId]?.handlerId, skipping unregisterCallback when absent) — and still send the plugin:event|unlisten invoke so the backend side is cleaned up either way.
Platform and versions
tauri 2.11.5 (latest on crates.io); the unguarded line is unchanged on dev
@tauri-apps/api 2.11.1
macOS 26.5 / WKWebView (the lookup itself is platform-independent)
Independent confirmation from another project, plus a possible explanation for the non-repro above.
We hit this in a Tauri 2 desktop app (tauri 2.11.3, @tauri-apps/api2.11.1) and only found this issue after diagnosing it from the crate sources. Production Sentry data, macOS/WKWebView, across three of our app releases:
TypeError: undefined is not an object (evaluating 'listeners[eventId].handlerId')
mechanism: onunhandledrejection · handled: no
14 occurrences, 2 users, spread over five weeks — so it is rare per session but persistent in the field, not a dev-only artifact. Our stacks are minified, but the message is unambiguous and matches unlisten_js_script exactly.
Why unlisten() right after await listen() may not reproduce it
The generated script guards the per-event-name bucket before it dereferences the entry:
If the listener being torn down is the first ever for that event name in this webview, then when its registration eval hasn't landed yet the bucket doesn't exist either — listeners is undefined, the outer if is false, and nothing throws. The outer guard hides the bug in exactly the simplest case.
To land on the throw you need both halves at once:
the name bucket already exists — some earlier listener for the same event name registered at some point (the bucket is created with Object.defineProperty and is never removed, so one earlier registration is enough, even if it has since been unlistened); and
this listener's own entry is not in it yet — its registration eval is still in flight when unlisten runs.
So a suggested repro: listen() an event and let it settle, then listen() the same event name a second time and call the second unlisten immediately, without awaiting anything in between. React StrictMode produces this shape on its own (first mount creates the bucket; the second registration is torn down within the same tick), which matches where we see it. Every occurrence we have is on an event name with a prior subscription.
Offered as a reading of the script rather than a measured result — we have not built a minimal reproduction against the API example, and our own evidence is field telemetry.
The leak half is the part that bit us hardest
Agreeing with the original report and underlining it: because the throw is on the first line of _unlisten, invoke('plugin:event|unlisten', …) never runs, so the backend registration survives a "successful-looking" teardown. The unhandled rejection is the visible symptom; the leaked listener is the one with behavioural consequences.
For anyone arriving here from a Sentry alert, what we shipped as a stopgap: one wrapper around listen() that (a) .catches the unlisten so it can't surface as an unhandled rejection, and (b) gates delivery on a released flag, so a leaked registration fans out to nobody and the double-delivery after remount can't reach app code. That treats the symptoms, not the leak — retrying the same unlisten on a later tick, once the registration eval has landed, does clear the backend side too.
A guard at the source (listeners[eventId]?.handlerId, and still sending the plugin:event|unlisten invoke either way, as #15800 does) would make all of that unnecessary. Happy to test a patched build against our app if that would help move it along.
Confirming this on tauri 2.11.1 / @tauri-apps/api 2.11.1, with a different trigger that I think widens the impact beyond what the report currently claims.
The entry can be stale, not just not-yet-written. Our reproduction is not a fast unsubscribe. It is a webview whose window has been recreated while the Rust side still holds listener ids — a Vite HMR reload under tauri dev, and also an app relaunch after a panic. The registry is rebuilt empty, the previously returned unlisten functions are still reachable from React cleanups, and listeners[eventId] is therefore undefined for an entry that was written and is now gone.
The proposed guard (listeners[eventId]?.handlerId) fixes both cases identically, so this does not change the fix. It does mean the bug is not confined to StrictMode or to dev builds: any production build that reloads its webview can hit the same line.
A defensive caller cannot currently work around it. This is the part that cost us the most time. listen() resolves to async () => _unlisten(event, eventId), so the failure arrives as a rejected promise. But the declared type is:
typeUnlistenFn=()=>void;
Because the type says void, no caller attaches a .catch, and tsc is perfectly happy with every one of them. We had already written a try { unlisten() } catch {} around one call site specifically to defend against this exact error message — and it could never have worked, because a synchronous catch cannot see a rejection. The guard looked correct in review for weeks while the reports kept arriving.
Working around it in userland means going through a wrapper that coerces the return:
which requires knowing the declared type is wrong. So alongside guarding the lookup, it may be worth widening the declaration to () => void | Promise<void> (or () => Promise<void>, which is what it actually is). That would let callers handle the rejection deliberately rather than discovering it in their error tracker.
For what it is worth, we found this because our own crash reporter filed a report about its own listener teardown on its first run in production — so the failure is quite capable of reaching real users rather than staying in dev.
Activity
Legend-Master commentedon Jul 30, 2026
I can't seem to reproduce this, adding
unlisten() unlisten = undefinedto
tauri/examples/api/src/views/Communication.svelte
Lines 13 to 15 in 5ab3175
and press send event to rust gives me no error at all
davideme commentedon Aug 31, 2026
Independent confirmation from another project, plus a possible explanation for the non-repro above.
We hit this in a Tauri 2 desktop app (tauri
2.11.3,@tauri-apps/api2.11.1) and only found this issue after diagnosing it from the crate sources. Production Sentry data, macOS/WKWebView, across three of our app releases:14 occurrences, 2 users, spread over five weeks — so it is rare per session but persistent in the field, not a dev-only artifact. Our stacks are minified, but the message is unambiguous and matches
unlisten_js_scriptexactly.Why
unlisten()right afterawait listen()may not reproduce itThe generated script guards the per-event-name bucket before it dereferences the entry:
If the listener being torn down is the first ever for that event name in this webview, then when its registration eval hasn't landed yet the bucket doesn't exist either —
listenersisundefined, the outerifis false, and nothing throws. The outer guard hides the bug in exactly the simplest case.To land on the throw you need both halves at once:
Object.definePropertyand is never removed, so one earlier registration is enough, even if it has since been unlistened); andSo a suggested repro:
listen()an event and let it settle, thenlisten()the same event name a second time and call the second unlisten immediately, without awaiting anything in between. React StrictMode produces this shape on its own (first mount creates the bucket; the second registration is torn down within the same tick), which matches where we see it. Every occurrence we have is on an event name with a prior subscription.Offered as a reading of the script rather than a measured result — we have not built a minimal reproduction against the API example, and our own evidence is field telemetry.
The leak half is the part that bit us hardest
Agreeing with the original report and underlining it: because the throw is on the first line of
_unlisten,invoke('plugin:event|unlisten', …)never runs, so the backend registration survives a "successful-looking" teardown. The unhandled rejection is the visible symptom; the leaked listener is the one with behavioural consequences.For anyone arriving here from a Sentry alert, what we shipped as a stopgap: one wrapper around
listen()that (a).catches the unlisten so it can't surface as an unhandled rejection, and (b) gates delivery on areleasedflag, so a leaked registration fans out to nobody and the double-delivery after remount can't reach app code. That treats the symptoms, not the leak — retrying the same unlisten on a later tick, once the registration eval has landed, does clear the backend side too.A guard at the source (
listeners[eventId]?.handlerId, and still sending theplugin:event|unlisteninvoke either way, as #15800 does) would make all of that unnecessary. Happy to test a patched build against our app if that would help move it along.wizi89 commentedon Sep 4, 2026
Confirming this on
tauri2.11.1 /@tauri-apps/api2.11.1, with a different trigger that I think widens the impact beyond what the report currently claims.The entry can be stale, not just not-yet-written. Our reproduction is not a fast unsubscribe. It is a webview whose
windowhas been recreated while the Rust side still holds listener ids — a Vite HMR reload undertauri dev, and also an app relaunch after a panic. The registry is rebuilt empty, the previously returned unlisten functions are still reachable from React cleanups, andlisteners[eventId]is thereforeundefinedfor an entry that was written and is now gone.The proposed guard (
listeners[eventId]?.handlerId) fixes both cases identically, so this does not change the fix. It does mean the bug is not confined to StrictMode or to dev builds: any production build that reloads its webview can hit the same line.A defensive caller cannot currently work around it. This is the part that cost us the most time.
listen()resolves toasync () => _unlisten(event, eventId), so the failure arrives as a rejected promise. But the declared type is:Because the type says
void, no caller attaches a.catch, andtscis perfectly happy with every one of them. We had already written atry { unlisten() } catch {}around one call site specifically to defend against this exact error message — and it could never have worked, because a synchronous catch cannot see a rejection. The guard looked correct in review for weeks while the reports kept arriving.Working around it in userland means going through a wrapper that coerces the return:
which requires knowing the declared type is wrong. So alongside guarding the lookup, it may be worth widening the declaration to
() => void | Promise<void>(or() => Promise<void>, which is what it actually is). That would let callers handle the rejection deliberately rather than discovering it in their error tracker.For what it is worth, we found this because our own crash reporter filed a report about its own listener teardown on its first run in production — so the failure is quite capable of reaching real users rather than staying in dev.