fix: cleanup SpeechRecognition on component unmount#1826
fix: cleanup SpeechRecognition on component unmount#1826cxybd wants to merge 1 commit intoant-design:mainfrom
Conversation
- Add useEffect cleanup to stop recognition and clear event handlers - Prevents memory leak when component unmounts during recording - Fixes potential privacy issue with background recording - Wrapped stop() in try-catch as recognition might not be started
Summary of ChangesHello, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed! This pull request resolves a critical memory leak and resource management issue within the Highlights
🧠 New Feature in Public Preview: You can now enable Memory to help Gemini Code Assist learn from your team's feedback. This makes future code reviews more consistent and personalized to your project's style. Click here to enable Memory in your admin console. Changelog
Activity
Using Gemini Code AssistThe full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips. Invoking Gemini You can request assistance from Gemini at any point by creating a comment using either
Customization To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a Limitations & Feedback Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for GitHub and other Google products, sign up here. You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension. Footnotes
|
📝 Walkthrough演示该变更为语音识别组件的自定义 Hook 添加了清理逻辑,在组件卸载时停止识别、移除事件处理器并清空引用。使用 try-catch 包装以处理识别未启动的情况。 变更
代码审查工作量估算🎯 2 (Simple) | ⏱️ ~8 分钟 诗歌
🚥 Pre-merge checks | ✅ 2 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (2 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches🧪 Generate unit tests (beta)
📝 Coding Plan
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment Tip CodeRabbit can use Trivy to scan for security misconfigurations and secrets in Infrastructure as Code files.Add a .trivyignore file to your project to customize which findings Trivy reports. |
There was a problem hiding this comment.
Code Review
This pull request correctly addresses a memory leak by adding a cleanup effect for the SpeechRecognition instance. The implementation is mostly correct. I've added one comment to refine the cleanup logic to prevent potential state updates on an unmounted component, which could cause warnings in React.
| if (recognitionRef.current) { | ||
| try { | ||
| recognitionRef.current.stop(); | ||
| } catch (e) { | ||
| // Recognition might not be started | ||
| } | ||
| recognitionRef.current.onstart = null; | ||
| recognitionRef.current.onend = null; | ||
| recognitionRef.current.onresult = null; | ||
| recognitionRef.current = null; | ||
| } |
There was a problem hiding this comment.
The current cleanup logic calls recognitionRef.current.stop() before nullifying the event handlers. The stop() method can trigger the onend event handler, which in turn calls setRecording(false). Since this cleanup function runs on component unmount, this will cause a state update on an unmounted component, leading to a warning from React.
To prevent this, the event handlers should be nullified before calling stop(). It's also slightly cleaner to store recognitionRef.current in a local variable to avoid repeated property access.
const recognition = recognitionRef.current;
if (recognition) {
// Nullify handlers first to prevent state updates on an unmounted component.
recognition.onstart = null;
recognition.onend = null;
recognition.onresult = null;
try {
recognition.stop();
} catch (e) {
// Recognition might not be started
}
recognitionRef.current = null;
}
Bundle ReportChanges will increase total bundle size by 1.61MB (78.51%) ⬆️
Affected Assets, Files, and Routes:view changes for bundle: antdx-array-pushAssets Changed:
|
There was a problem hiding this comment.
🧹 Nitpick comments (1)
packages/x/components/sender/hooks/use-speech.ts (1)
140-149: 建议在调用stop()前先解绑事件处理器,防止卸载阶段回调触发导致状态更新。根据 Web Speech API 规范,调用
stop()后onend和onresult仍可能触发(服务可能继续返回已收集音频的识别结果)。当前代码在 Line 142 先执行stop(),再在 Line 146-148 置空回调处理器,存在回调在组件卸载期间仍被执行并修改状态的风险。更安全的做法是先置空处理器,再调用stop(),可有效避免这类竞态问题。参考调整方案
React.useEffect(() => { return () => { if (recognitionRef.current) { + const recognition = recognitionRef.current; + recognition.onstart = null; + recognition.onend = null; + recognition.onresult = null; try { - recognitionRef.current.stop(); + recognition.stop(); } catch (e) { // Recognition might not be started } - recognitionRef.current.onstart = null; - recognitionRef.current.onend = null; - recognitionRef.current.onresult = null; recognitionRef.current = null; } }; }, []);🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/x/components/sender/hooks/use-speech.ts` around lines 140 - 149, In the use-speech hook, avoid calling recognitionRef.current.stop() before clearing event handlers because onend/onresult may still fire and update state during unmount; update the teardown to first null out recognitionRef.current.onstart/onend/onresult (and any other handlers) and only then call recognitionRef.current.stop(), finally set recognitionRef.current = null so callbacks cannot run after stop(); target the block that currently calls recognitionRef.current.stop() and then clears handlers to perform the handler unbinding first.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Nitpick comments:
In `@packages/x/components/sender/hooks/use-speech.ts`:
- Around line 140-149: In the use-speech hook, avoid calling
recognitionRef.current.stop() before clearing event handlers because
onend/onresult may still fire and update state during unmount; update the
teardown to first null out recognitionRef.current.onstart/onend/onresult (and
any other handlers) and only then call recognitionRef.current.stop(), finally
set recognitionRef.current = null so callbacks cannot run after stop(); target
the block that currently calls recognitionRef.current.stop() and then clears
handlers to perform the handler unbinding first.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro
Run ID: 53693f3f-9ac8-43b9-ab50-ece6a7413d8e
📒 Files selected for processing (1)
packages/x/components/sender/hooks/use-speech.ts
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #1826 +/- ##
=======================================
Coverage 97.42% 97.42%
=======================================
Files 149 149
Lines 5044 5053 +9
Branches 1449 1440 -9
=======================================
+ Hits 4914 4923 +9
Misses 128 128
Partials 2 2 ☔ View full report in Codecov by Sentry. 🚀 New features to boost your workflow:
|

🐛 Bug Description
Found a memory leak in
useSpeechhook whereSpeechRecognitioninstance is not cleaned up on component unmount.Issue
The
SpeechRecognitioninstance created inensureRecognition()is stored inrecognitionRefbut never cleaned up, causing:Fix
Added
useEffectcleanup to:🔧 Changes
packages/x/components/sender/hooks/use-speech.ts✅ Testing
📊 Severity
High - Affects all Sender components using speech recognition feature
Summary by CodeRabbit
发布说明