Skip to content

unlisten throws and leaks the listener when called before the registration eval lands (listeners[eventId] undefined) #15799

Closed

Description

@karpov2

Describe the bug

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):

const listeners = (window['__TAURI_EVENT_LISTENERS__'] || {})[event]
if (listeners) {
  window.__TAURI_INTERNALS__.unregisterCallback(listeners[eventId].handlerId) // ← throws
}

— 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:
const un = await listen("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)

Activity

  1. Legend-Master commented on Jul 30, 2026

    @Legend-Master
    Contributor

    I can't seem to reproduce this, adding

        unlisten()
        unlisten = undefined

    to

    onMount(async () => {
    unlisten = await webviewWindow.listen('rust-event', onMessage)
    })

    and press send event to rust gives me no error at all

  2. davideme commented on Aug 31, 2026

    @davideme

    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/api 2.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:

    const listeners = (window['__TAURI_EVENT_LISTENERS__'] || {})[event]
    if (listeners) {
      window.__TAURI_INTERNALS__.unregisterCallback(listeners[eventId].handlerId)
    }

    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:

    1. 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
    2. 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.

  3. wizi89 commented on Sep 4, 2026

    @wizi89

    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:

    type UnlistenFn = () => 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:

    void Promise.resolve((fn as () => unknown)()).catch(() => {});

    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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    status: needs more infoIssue needs more information, discussion or reproducible examplestatus: needs triageThis issue needs to triage, applied to new issuestype: bug

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions