Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions packages/x/components/sender/hooks/use-speech.ts
Original file line number Diff line number Diff line change
Expand Up @@ -134,5 +134,22 @@ export default function useSpeech(
}
});

// Cleanup SpeechRecognition on component unmount
React.useEffect(() => {
return () => {
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;
}
Comment on lines +140 to +150

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

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;
      }

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

PR 的动机和方向完全合理,但实现有一个关键顺序问题——需要先置空事件处理器再调用
stop(),否则会在组件卸载时触发 React 状态更新警告。建议作者采纳 CodeRabbit/Gemini 的建议调整顺序后合并。

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

+1

};
}, []);

return [mergedAllowSpeech, triggerSpeech, recording] as const;
}
Loading