Skip to content

Commit d981d90

Browse files
committed
修复自动重启异步清理竞态
1 parent 4cee0f3 commit d981d90

1 file changed

Lines changed: 10 additions & 2 deletions

File tree

app/explore.tsx

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -78,6 +78,7 @@ export default function ExploreScreen() {
7878
const isRecordingRef = useRef(false);
7979
const restartTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
8080
const restartInFlightRef = useRef(false);
81+
const restartScopeRef = useRef(0);
8182

8283
const { config: connectionConfig, setConfig: setConnectionConfig } = useDevConnectionConfig();
8384

@@ -126,6 +127,7 @@ export default function ExploreScreen() {
126127
useEffect(() => {
127128
console.log('ExploreScreen 组件初始化');
128129

130+
restartScopeRef.current += 1;
129131
audioServiceRef.current?.destroy();
130132
audioServiceRef.current = new AudioService({
131133
host: connectionConfig.host,
@@ -155,6 +157,7 @@ export default function ExploreScreen() {
155157
});
156158

157159
return () => {
160+
restartScopeRef.current += 1;
158161
if (restartTimerRef.current) {
159162
clearTimeout(restartTimerRef.current);
160163
restartTimerRef.current = null;
@@ -235,21 +238,26 @@ export default function ExploreScreen() {
235238
return;
236239
}
237240
restartInFlightRef.current = true;
241+
const restartScope = restartScopeRef.current;
238242
console.log('检测到失联状态,执行自动重启会话');
239243
(async () => {
240244
try {
241245
await audioServiceRef.current?.endAICall();
242246
} catch (e) {
243247
console.warn('自动重启:结束会话失败(可忽略)', e);
244248
}
249+
if (restartScopeRef.current !== restartScope) return;
245250
restartTimerRef.current = setTimeout(async () => {
251+
if (restartScopeRef.current !== restartScope) return;
246252
try {
247253
await audioServiceRef.current?.startAICall();
248254
} catch (e) {
249255
console.warn('自动重启:重启会话失败', e);
250256
} finally {
251-
restartTimerRef.current = null;
252-
restartInFlightRef.current = false;
257+
if (restartScopeRef.current === restartScope) {
258+
restartTimerRef.current = null;
259+
restartInFlightRef.current = false;
260+
}
253261
}
254262
}, 7500);
255263
})();

0 commit comments

Comments
 (0)