fix: 修复白屏 — SW networkFirst + initSession try/catch + Error Boundary

1. sw.js: /index.html 导航请求使用 networkFirst 策略替代 cacheFirst,
   避免旧 SW 缓存不存在的旧 hash 资源导致 404 白屏
2. App.tsx: initSession 添加 try/catch 异常保护,防止初始化
   失败导致整个 React 树崩溃
3. 新建 ErrorBoundary.tsx: React 错误边界组件,捕获渲染异常
   显示友好错误页面而非白屏
This commit is contained in:
2026-05-20 21:29:37 +08:00
parent 4058aae1e4
commit 76ef31e153
3 changed files with 167 additions and 66 deletions
+37 -6
View File
@@ -38,18 +38,28 @@ self.addEventListener('message', (event) => {
} }
}); });
// Fetch: 缓存优先策略(对 API 请求使用网络优先) // Fetch: HTML 导航请求使用 networkFirst,静态资源使用 cacheFirst
self.addEventListener('fetch', (event) => { self.addEventListener('fetch', (event) => {
const url = new URL(event.request.url); const url = new URL(event.request.url);
// API 请求:网络优先,失败时返回离线 JSON
if (url.pathname.startsWith('/api/')) {
event.respondWith(networkFirst(event.request));
} else if (url.pathname.startsWith('/ws')) {
// WebSocket 连接不缓存 // WebSocket 连接不缓存
if (url.pathname.startsWith('/ws')) {
event.respondWith(fetch(event.request)); event.respondWith(fetch(event.request));
return;
}
// 导航请求(HTML 页面):网络优先,避免旧缓存引用不存在的 hash 资源 → 白屏
const isNavigation =
event.request.mode === 'navigate' ||
(event.request.headers.get('Accept') || '').includes('text/html');
if (isNavigation) {
event.respondWith(networkFirstForHTML(event.request));
} else if (url.pathname.startsWith('/api/')) {
// API 请求:网络优先,失败时返回离线 JSON
event.respondWith(networkFirst(event.request));
} else { } else {
// 静态资源:缓存优先 // 静态资源JS/CSS/图片等):缓存优先
event.respondWith(cacheFirst(event.request)); event.respondWith(cacheFirst(event.request));
} }
}); });
@@ -73,6 +83,27 @@ async function cacheFirst(request) {
} }
} }
async function networkFirstForHTML(request) {
try {
const response = await fetch(request);
if (response.ok) {
const cache = await caches.open(CACHE_NAME);
cache.put(request, response.clone());
}
return response;
} catch (e) {
const cached = await caches.match(request);
if (cached) return cached;
// 最终 fallback:离线页面
const offline = await caches.match('/offline.html');
if (offline) return offline;
return new Response('离线状态,请检查网络连接', {
status: 503,
headers: { 'Content-Type': 'text/plain; charset=utf-8' },
});
}
}
async function networkFirst(request) { async function networkFirst(request) {
try { try {
const response = await fetch(request); const response = await fetch(request);
+9
View File
@@ -2,6 +2,7 @@ import { useState, useEffect, useCallback, useRef } from 'react';
import { AppLayout } from '@/components/layout/AppLayout'; import { AppLayout } from '@/components/layout/AppLayout';
import { ChatContainer } from '@/components/chat/ChatContainer'; import { ChatContainer } from '@/components/chat/ChatContainer';
import { ChatInput } from '@/components/chat/ChatInput'; import { ChatInput } from '@/components/chat/ChatInput';
import { ErrorBoundary } from '@/components/ErrorBoundary';
import { useAuth } from '@/hooks/useAuth'; import { useAuth } from '@/hooks/useAuth';
import { useChat } from '@/hooks/useChat'; import { useChat } from '@/hooks/useChat';
import { useSessionStore, isAdminUser } from '@/store/sessionStore'; import { useSessionStore, isAdminUser } from '@/store/sessionStore';
@@ -58,6 +59,7 @@ export default function App() {
if (!userId || initializedRef.current) return; if (!userId || initializedRef.current) return;
initializedRef.current = true; initializedRef.current = true;
try {
const admin = isAdminUser(userId); const admin = isAdminUser(userId);
// 1. 从服务端加载会话列表 // 1. 从服务端加载会话列表
@@ -120,6 +122,11 @@ export default function App() {
setHashSessionId(latest.id); setHashSessionId(latest.id);
await loadMessagesFromServer(latest.id); await loadMessagesFromServer(latest.id);
} }
} catch (error) {
console.error('[App] initSession failed:', error);
// 重置状态避免死锁,允许后续重试
initializedRef.current = false;
}
}, [userId, loadSessionsFromServer, ensureMainSession, setCurrentSessionId, setMessages, loadMessagesFromServer]); }, [userId, loadSessionsFromServer, ensureMainSession, setCurrentSessionId, setMessages, loadMessagesFromServer]);
// 登录后初始化 // 登录后初始化
@@ -317,6 +324,7 @@ export default function App() {
// 聊天界面 // 聊天界面
return ( return (
<ErrorBoundary>
<AppLayout> <AppLayout>
<div className="flex flex-col h-full overflow-hidden"> <div className="flex flex-col h-full overflow-hidden">
<div className="flex-1 min-h-0 overflow-hidden"> <div className="flex-1 min-h-0 overflow-hidden">
@@ -325,5 +333,6 @@ export default function App() {
<ChatInput onSend={send} /> <ChatInput onSend={send} />
</div> </div>
</AppLayout> </AppLayout>
</ErrorBoundary>
); );
} }
@@ -0,0 +1,61 @@
import React, { Component, ErrorInfo, ReactNode } from 'react'
interface Props {
children: ReactNode
fallback?: ReactNode
}
interface State {
hasError: boolean
error: Error | null
}
export class ErrorBoundary extends Component<Props, State> {
constructor(props: Props) {
super(props)
this.state = { hasError: false, error: null }
}
static getDerivedStateFromError(error: Error): State {
return { hasError: true, error }
}
componentDidCatch(error: Error, errorInfo: ErrorInfo) {
console.error('[ErrorBoundary] Caught error:', error, errorInfo)
}
handleReset = () => {
this.setState({ hasError: false, error: null })
}
render() {
if (this.state.hasError) {
if (this.props.fallback) return this.props.fallback
return (
<div style={{
display: 'flex', flexDirection: 'column', alignItems: 'center',
justifyContent: 'center', height: '100vh', padding: '2rem',
background: '#0f172a', color: '#e2e8f0', fontFamily: 'system-ui'
}}>
<h1 style={{ fontSize: '1.5rem', marginBottom: '0.5rem' }}> </h1>
<p style={{ color: '#94a3b8', marginBottom: '1rem', maxWidth: '400px', textAlign: 'center' }}>
{this.state.error?.message || '未知错误'}
</p>
<button
onClick={this.handleReset}
style={{
padding: '0.5rem 1.5rem', borderRadius: '0.5rem',
background: '#3b82f6', color: 'white', border: 'none',
cursor: 'pointer', fontSize: '0.875rem'
}}
>
</button>
</div>
)
}
return this.props.children
}
}
export default ErrorBoundary