fix: stop YouTube mute-check interval when player is destroyed

The setInterval polling playerRef.current.isMuted() continued running
after the YouTube player was destroyed, causing repeated TypeErrors.
Now the interval self-clears when it detects the player is invalid.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
codytseng 2026-03-16 22:08:51 +08:00
parent cd86b3aac5
commit 67f308e47f

View file

@ -55,7 +55,7 @@ const Player = memo(({ videoId, isShort, className }: PlayerProps) => {
} }
}) })
let checkMutedInterval: NodeJS.Timeout | null = null let checkMutedInterval: ReturnType<typeof setInterval> | null = null
function initPlayer() { function initPlayer() {
try { try {
if (!videoId || !containerRef.current || !window.YT.Player || unmountedRef.current) return if (!videoId || !containerRef.current || !window.YT.Player || unmountedRef.current) return
@ -87,20 +87,29 @@ const Player = memo(({ videoId, isShort, className }: PlayerProps) => {
} }
setInitSuccess(true) setInitSuccess(true)
checkMutedInterval = setInterval(() => { checkMutedInterval = setInterval(() => {
if (playerRef.current && !unmountedRef.current) { if (
const mute = playerRef.current.isMuted() !playerRef.current ||
if (mute !== currentMuteState) { unmountedRef.current ||
currentMuteState = mute typeof playerRef.current.isMuted !== 'function'
) {
if (checkMutedInterval) {
clearInterval(checkMutedInterval)
checkMutedInterval = null
}
return
}
const mute = playerRef.current.isMuted()
if (mute !== currentMuteState) {
currentMuteState = mute
if (mute !== muteStateRef.current) { if (mute !== muteStateRef.current) {
updateMuteMedia(currentMuteState) updateMuteMedia(currentMuteState)
} }
} else if (muteStateRef.current !== mute) { } else if (muteStateRef.current !== mute) {
if (muteStateRef.current) { if (muteStateRef.current) {
playerRef.current.mute() playerRef.current.mute()
} else { } else {
playerRef.current.unMute() playerRef.current.unMute()
}
} }
} }
}, 200) }, 200)