From b77358941d0334770dd0fb138a95e1291303162d Mon Sep 17 00:00:00 2001 From: Dylan Audius Date: Thu, 12 Nov 2026 09:47:58 -0800 Subject: [PATCH] fix: remove leaked listeners and catch unhandled rejections Contained fixes from #14665 with no intended UX change: - harmony Modal: remove the touchmove listener on close/unmount - harmony Slider: detach document drag listeners on unmount - mobile GoogleCast: remove the PlaybackActiveTrackChanged listener - mobile Airplay: call remove() on the subscription (stop() doesn't exist) - mobile useRevertOnCancel: return the unsubscribe from addListener - mobile audius-sdk: init waiters use once() - mobile ChatScreen: add deps so the AppState listener isn't re-added each render - web StripeOnRampModal: remove onramp_session_updated listener; catch init failure - web foregroundPollingDaemon: remove visibilitychange listener on cancel - common uuid(): variant digit came from a string bitwise op Co-Authored-By: Claude Opus 5.5 --- packages/common/src/utils/uid.ts | 10 +---- .../harmony/src/components/modal/Modal.tsx | 27 ++++++----- .../src/components/scrubber/Slider.tsx | 18 ++++++++ .../mobile/src/components/audio/Airplay.tsx | 5 ++- .../src/components/audio/GoogleCast.tsx | 23 ++++++++-- .../src/screens/chat-screen/ChatScreen.tsx | 2 +- .../screens/form-screen/useRevertOnCancel.ts | 7 +-- .../mobile/src/services/sdk/audius-sdk.ts | 2 +- .../StripeOnRampModal.tsx | 9 +++- packages/web/src/utils/sagaPollingDaemons.ts | 45 ++++++++++--------- 10 files changed, 91 insertions(+), 57 deletions(-) diff --git a/packages/common/src/utils/uid.ts b/packages/common/src/utils/uid.ts index de2dd4dacc1..88aa56bf8ab 100644 --- a/packages/common/src/utils/uid.ts +++ b/packages/common/src/utils/uid.ts @@ -147,19 +147,13 @@ export const getNumericIdFromUid = (uid: string) => export const uuid = () => { // https://stackoverflow.com/questions/105034/create-guid-uuid-in-javascript/873856#873856 - const s = [] + const s: string[] = [] const hexDigits = '0123456789abcdef' - // all the ts-ignores are needed so the mobile package types things correctly - // remove when upgrading to latest typescript for (let i = 0; i < 36; i++) { - // @ts-ignore s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1) } - // @ts-ignore s[14] = '4' // bits 12-15 of the time_hi_and_version field to 0010 - // @ts-ignore - s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1) // bits 6-7 of the clock_seq_hi_and_reserved to 01 - // @ts-ignore + s[19] = hexDigits.substr((parseInt(s[19], 16) & 0x3) | 0x8, 1) // bits 6-7 of the clock_seq_hi_and_reserved to 01 s[8] = s[13] = s[18] = s[23] = '-' const uuid = s.join('') diff --git a/packages/harmony/src/components/modal/Modal.tsx b/packages/harmony/src/components/modal/Modal.tsx index 51c75bbe785..eb38a7cb4a4 100644 --- a/packages/harmony/src/components/modal/Modal.tsx +++ b/packages/harmony/src/components/modal/Modal.tsx @@ -228,22 +228,21 @@ export const Modal = forwardRef(function Modal( }, [isOpenProp, modalState]) useEffect(() => { - if (isOpen) { - if (bgModal) { - bgModal.classList.add('bgModalVisible') - } + if (!isOpen) { + if (bgModal) bgModal.classList.remove('bgModalVisible') + return + } - // Need to prevent safari iOS bounce - // overscroll effect by intercepting - // touchmove events. - if (modalRoot) modalRoot.addEventListener('touchmove', onTouchMove) - return () => { - if (bgModal) bgModal.classList.remove('bgModalVisible') - } + if (bgModal) bgModal.classList.add('bgModalVisible') + + // Need to prevent safari iOS bounce + // overscroll effect by intercepting + // touchmove events. + if (modalRoot) modalRoot.addEventListener('touchmove', onTouchMove) + return () => { + if (bgModal) bgModal.classList.remove('bgModalVisible') + if (modalRoot) modalRoot.removeEventListener('touchmove', onTouchMove) } - if (bgModal) bgModal.classList.remove('bgModalVisible') - if (modalRoot) modalRoot.removeEventListener('touchmove', onTouchMove) - return () => {} }, [isOpen, bgModal, onTouchMove, modalRoot]) const transition = useTransition(isOpenProp, null, { diff --git a/packages/harmony/src/components/scrubber/Slider.tsx b/packages/harmony/src/components/scrubber/Slider.tsx index 24a2fa1d960..5b35d44ff40 100644 --- a/packages/harmony/src/components/scrubber/Slider.tsx +++ b/packages/harmony/src/components/scrubber/Slider.tsx @@ -228,6 +228,24 @@ export const Slider = ({ setDragPercentTouch(e) } + // Detach any in-progress drag listeners if unmounted mid-drag + useEffect(() => { + return () => { + if (mouseMoveRef.current) { + document.removeEventListener('mousemove', mouseMoveRef.current) + } + if (mouseUpRef.current) { + document.removeEventListener('mouseup', mouseUpRef.current) + } + if (touchMoveRef.current) { + document.removeEventListener('touchmove', touchMoveRef.current) + } + if (touchEndRef.current) { + document.removeEventListener('touchend', touchEndRef.current) + } + } + }, []) + // Watch interactions to the scrubber and call to animate useEffect(() => { if (!dragPercent.current) { diff --git a/packages/mobile/src/components/audio/Airplay.tsx b/packages/mobile/src/components/audio/Airplay.tsx index fea0407bbbf..5daf161c868 100644 --- a/packages/mobile/src/components/audio/Airplay.tsx +++ b/packages/mobile/src/components/audio/Airplay.tsx @@ -1,6 +1,7 @@ import { useCallback, useEffect, useRef } from 'react' import { castActions } from '@audius/common/store' +import type { EmitterSubscription } from 'react-native' import { requireNativeComponent, NativeEventEmitter, @@ -36,7 +37,7 @@ export const useAirplay = () => { * codebase. */ const Airplay = () => { - const listenerRef = useRef(null) + const listenerRef = useRef(null) const dispatch = useDispatch() useEffect(() => { @@ -68,7 +69,7 @@ const Airplay = () => { ) return () => { - listenerRef.current?.stop?.() + listenerRef.current?.remove() } }, [listenerRef, dispatch]) diff --git a/packages/mobile/src/components/audio/GoogleCast.tsx b/packages/mobile/src/components/audio/GoogleCast.tsx index 251662b2dd1..20fd40f1fbe 100644 --- a/packages/mobile/src/components/audio/GoogleCast.tsx +++ b/packages/mobile/src/components/audio/GoogleCast.tsx @@ -18,7 +18,7 @@ import { } from 'react-native-google-cast' import TrackPlayer, { Event } from 'react-native-track-player' import { useDispatch, useSelector } from 'react-redux' -import { useAsync, usePrevious } from 'react-use' +import { usePrevious } from 'react-use' const { setIsCasting } = castActions const { getPlaying, getSeek, getCounter } = playbackSelectors @@ -118,16 +118,23 @@ export const useChromecast = () => { }, [prevTrack, track, counter, internalCounter, setInternalCounter]) // Load media when the cast connects - useAsync(async () => { - if (castState === CastState.CONNECTED) { + useEffect(() => { + if (castState !== CastState.CONNECTED) return + let cancelled = false + let activeTrackSubscription: + | ReturnType + | undefined + + const load = async () => { const { position: currentPosition } = await TrackPlayer.getProgress() const currentPlaying = await TrackPlayer.getActiveTrack() + if (cancelled) return if (currentPlaying) { loadCast(track, currentPosition, currentPlaying?.url) } else { // If nothing is currently playing, listen for something to start // playing and then load it to cast. - TrackPlayer.addEventListener( + activeTrackSubscription = TrackPlayer.addEventListener( Event.PlaybackActiveTrackChanged, async () => { const { position: currentPosition } = @@ -138,6 +145,14 @@ export const useChromecast = () => { ) } } + load().catch((e) => { + console.error('Failed to load media onto cast device', e) + }) + + return () => { + cancelled = true + activeTrackSubscription?.remove() + } }, [castState, track, loadCast]) // Play & pause the cast device diff --git a/packages/mobile/src/screens/chat-screen/ChatScreen.tsx b/packages/mobile/src/screens/chat-screen/ChatScreen.tsx index 3c352a60860..5ace93f6214 100644 --- a/packages/mobile/src/screens/chat-screen/ChatScreen.tsx +++ b/packages/mobile/src/screens/chat-screen/ChatScreen.tsx @@ -220,7 +220,7 @@ const useGetLatestMessages = ( // Remove listener on unmount return () => handle.remove() - }) + }, [fetchLatestMessagesCallback]) } const ChatScreenContent = () => { diff --git a/packages/mobile/src/screens/form-screen/useRevertOnCancel.ts b/packages/mobile/src/screens/form-screen/useRevertOnCancel.ts index 3eba398d722..db58bcf2352 100644 --- a/packages/mobile/src/screens/form-screen/useRevertOnCancel.ts +++ b/packages/mobile/src/screens/form-screen/useRevertOnCancel.ts @@ -13,14 +13,11 @@ export const useRevertOnCancel = (active?: boolean) => { useEffect(() => { if (!active || !initialValues) return - const listener = navigation.addListener('beforeRemove', ({ data }) => { + // addListener returns an unsubscribe function (not the listener itself) + return navigation.addListener('beforeRemove', ({ data }) => { if (data.action.type === 'POP') { setValues(initialValues) } }) - - return () => { - navigation.removeListener('beforeRemove', listener) - } }, [navigation, initialValues, setValues, active]) } diff --git a/packages/mobile/src/services/sdk/audius-sdk.ts b/packages/mobile/src/services/sdk/audius-sdk.ts index 63c5739a372..a5359885bcc 100644 --- a/packages/mobile/src/services/sdk/audius-sdk.ts +++ b/packages/mobile/src/services/sdk/audius-sdk.ts @@ -60,7 +60,7 @@ const initSdk = async () => { export const audiusSdk = async () => { if (inProgress) { await new Promise((resolve) => { - sdkEventEmitter.addListener(SDK_LOADED_EVENT_NAME, resolve) + sdkEventEmitter.once(SDK_LOADED_EVENT_NAME, resolve) }) return sdkInstance } else if (!sdkInstance) { diff --git a/packages/web/src/components/stripe-on-ramp-modal/StripeOnRampModal.tsx b/packages/web/src/components/stripe-on-ramp-modal/StripeOnRampModal.tsx index b3326ff95bf..d25692aa0ba 100644 --- a/packages/web/src/components/stripe-on-ramp-modal/StripeOnRampModal.tsx +++ b/packages/web/src/components/stripe-on-ramp-modal/StripeOnRampModal.tsx @@ -38,6 +38,9 @@ const MountStripeSession = ({ session }: { session: OnrampSession }) => { } session.mount('#stripe-onramp-modal') session.addEventListener('onramp_session_updated', handleSessionUpdate) + return () => { + session.removeEventListener('onramp_session_updated', handleSessionUpdate) + } }, [session, handleSessionUpdate]) return ( @@ -78,7 +81,11 @@ export const StripeOnRampModal = () => { clientSecret: stripeClientSecret }) } - initializeStripeSession().then(setSession) + initializeStripeSession() + .then(setSession) + .catch((e) => { + console.error('Failed to initialize Stripe onramp session', e) + }) } }, [isOpen, stripeClientSecret]) diff --git a/packages/web/src/utils/sagaPollingDaemons.ts b/packages/web/src/utils/sagaPollingDaemons.ts index 1bd83096079..62f485aba90 100644 --- a/packages/web/src/utils/sagaPollingDaemons.ts +++ b/packages/web/src/utils/sagaPollingDaemons.ts @@ -21,33 +21,36 @@ export function* foregroundPollingDaemon( const isNativeMobile = yield* getContext('isNativeMobile') let isBrowserInBackground = false + const handleVisibilityChange = () => { + isBrowserInBackground = document.hidden + } if (!isNativeMobile) { - document.addEventListener( - 'visibilitychange', - () => { - if (document.hidden) { - isBrowserInBackground = true - } else { - isBrowserInBackground = false - } - }, - false - ) + document.addEventListener('visibilitychange', handleVisibilityChange, false) } - while (true) { - if (!isBrowserInBackground || isElectron() || isNativeMobile) { - yield put(action) - } - if (customDelayTimeConfig && !isNativeMobile) { - const currentRoute: string = yield select(getLocationPathname) - if (customDelayTimeConfig[currentRoute]) { - yield delay(customDelayTimeConfig[currentRoute]) + try { + while (true) { + if (!isBrowserInBackground || isElectron() || isNativeMobile) { + yield put(action) + } + if (customDelayTimeConfig && !isNativeMobile) { + const currentRoute: string = yield select(getLocationPathname) + if (customDelayTimeConfig[currentRoute]) { + yield delay(customDelayTimeConfig[currentRoute]) + } else { + yield delay(defaultDelayTimeMs) + } } else { yield delay(defaultDelayTimeMs) } - } else { - yield delay(defaultDelayTimeMs) + } + } finally { + if (!isNativeMobile) { + document.removeEventListener( + 'visibilitychange', + handleVisibilityChange, + false + ) } } }