fix: improve TUN mode handling logic to prevent unnecessary state changes #5122 (#5124)

This commit is contained in:
Tunglies
2025-10-20 16:09:29 +08:00
committed by GitHub
parent 8ebf915330
commit a1dcdd04a7

View File

@@ -1,4 +1,4 @@
import { useEffect } from "react"; import { useCallback, useEffect, useRef } from "react";
import { useTranslation } from "react-i18next"; import { useTranslation } from "react-i18next";
import useSWR from "swr"; import useSWR from "swr";
@@ -8,7 +8,8 @@ import { showNotice } from "@/services/noticeService";
export const useVerge = () => { export const useVerge = () => {
const { t } = useTranslation(); const { t } = useTranslation();
const { isTunModeAvailable, isLoading } = useSystemState(); const { isTunModeAvailable, isServiceMode, isLoading } = useSystemState();
const disablingRef = useRef(false);
const { data: verge, mutate: mutateVerge } = useSWR( const { data: verge, mutate: mutateVerge } = useSWR(
"getVergeConfig", "getVergeConfig",
@@ -25,25 +26,50 @@ export const useVerge = () => {
const { enable_tun_mode } = verge ?? {}; const { enable_tun_mode } = verge ?? {};
// 当服务不可用且TUN模式开启时自动关闭TUN const mutateVergeRef = useRef(mutateVerge);
useEffect(() => { const tRef = useRef(t);
if (enable_tun_mode && !isTunModeAvailable && !isLoading) { const enableTunRef = useRef(enable_tun_mode);
console.log("[useVerge] 检测到服务不可用自动关闭TUN模式"); const isLoadingRef = useRef(isLoading);
const isServiceModeRef = useRef(isServiceMode);
patchVergeConfig({ enable_tun_mode: false }) mutateVergeRef.current = mutateVerge;
.then(() => { tRef.current = t;
mutateVerge(); enableTunRef.current = enable_tun_mode;
showNotice( isLoadingRef.current = isLoading;
"info", isServiceModeRef.current = isServiceMode;
t("TUN Mode automatically disabled due to service unavailable"),
); const doDisable = useCallback(async () => {
}) try {
.catch((err) => { if (isServiceModeRef.current === true) return;
console.error("[useVerge] 自动关闭TUN模式失败:", err); await patchVergeConfig({ enable_tun_mode: false });
showNotice("error", t("Failed to disable TUN Mode automatically")); await mutateVergeRef.current?.();
}); showNotice(
"info",
tRef.current(
"TUN Mode automatically disabled due to service unavailable",
),
);
} catch (err) {
console.error("[useVerge] 自动关闭TUN模式失败:", err);
showNotice(
"error",
tRef.current("Failed to disable TUN Mode automatically"),
);
} finally {
disablingRef.current = false;
} }
}, [isTunModeAvailable, isLoading, enable_tun_mode, mutateVerge, t]); }, []);
useEffect(() => {
if (isTunModeAvailable === true) return;
if (isLoadingRef.current === true) return;
if (enableTunRef.current !== true) return;
if (isServiceModeRef.current === true) return;
if (disablingRef.current) return;
disablingRef.current = true;
void doDisable();
}, [isTunModeAvailable, doDisable]);
return { return {
verge, verge,