fix: prevent promise errors in async operations after component unmount

This commit addresses the "Uncaught (in promise) Error: A listener indicated an asynchronous response by returning true, but the message channel closed before a response was received" error that occurs when async operations attempt to update state after component unmount.

Changes:

- Add component mount status tracking with useRef in App.tsx and DocumentManager.tsx
- Implement beforeunload event listeners to handle page reload scenarios
- Add mount status checks before and after async operations
- Add try-catch blocks to properly handle errors in async operations
- Ensure state updates only occur when components are still mounted
- Prevent health check and document polling from causing errors during unmount
This commit is contained in:
yangdx
2025-04-07 06:04:18 +08:00
parent 4c5229bb76
commit d2efc80fad
2 changed files with 100 additions and 23 deletions

View File

@@ -33,6 +33,26 @@ function App() {
}
}, [])
// Track component mount status with useRef
const isMountedRef = useRef(true);
// Set up mount/unmount status tracking
useEffect(() => {
isMountedRef.current = true;
// Handle page reload/unload
const handleBeforeUnload = () => {
isMountedRef.current = false;
};
window.addEventListener('beforeunload', handleBeforeUnload);
return () => {
isMountedRef.current = false;
window.removeEventListener('beforeunload', handleBeforeUnload);
};
}, []);
// Health check - can be disabled
useEffect(() => {
// Only execute if health check is enabled and ApiKeyAlert is closed
@@ -40,7 +60,14 @@ function App() {
// Health check function
const performHealthCheck = async () => {
await useBackendState.getState().check();
try {
// Only perform health check if component is still mounted
if (isMountedRef.current) {
await useBackendState.getState().check();
}
} catch (error) {
console.error('Health check error:', error);
}
};
// Set interval for periodic execution