使用 Background Sync 在恢复网络后重试失败 mutation。
解读
在国内一线/二线大厂的 React+Redux 项目中,弱网、地铁、电梯等场景导致 mutation(POST/PUT/DELETE)失败率高达 15% 以上。
面试官想确认两点:
- 你是否理解 Redux 数据流中“副作用”与“状态”的边界;
- 你是否能把浏览器原生 Background Sync API 与 Redux 生态结合,实现“断网缓存、有网重试、顺序保序、幂等安全”的完整闭环,而不是简单调个 setTimeout 重试。
知识点
- Redux 副作用隔离:失败请求应落盘到 Redux 状态,而非仅存在组件内存。
- Background Sync 生命周期:
- 注册 sync 事件需借助 Service Worker;
- 触发时机由浏览器调度,不保证立即执行,但保证“有网后一定会执行一次”。
- mutation 幂等:国内业务常要求“客户端生成 UUID + 服务端去重表”双保险,防止重试造成资损。
- IndexedDB 选型:localStorage 同步阻塞主线程,IndexedDB 异步 + 大容量 更适合缓存失败请求体。
- redux-persist 与自定义根 Saga 的协作:persist 把队列落盘,根 Saga 监听 SW 的 postMessage,实现“重试完再清理”。
答案
- 定义队列型状态
interface RetryQueueItem {
id: string; // 客户端 UUID
endpoint: string;
method: 'POST' | 'PUT' | 'DELETE';
payload: any;
timestamp: number;
}
type RootState = {
network: { online: boolean };
retryQueue: RetryQueueItem[];
};
- 在 Redux Toolkit 的 extraReducers 里,对 mutation rejected 做统一处理
.addMatcher(
isMutationRejected, // RTK Query 工具函数
(state, action) => {
const item: RetryQueueItem = {
id: uuid(),
endpoint: action.meta.arg.endpointName,
method: action.meta.arg.originalArgs.method,
payload: action.meta.arg.originalArgs.body,
timestamp: Date.now()
};
state.retryQueue.push(item);
// 立即注册 Background Sync
if ('serviceWorker' in navigator && 'sync' in ServiceWorkerRegistration.prototype) {
navigator.serviceWorker.ready.then(reg => reg.sync.register('retry-mutation'));
}
}
)
- Service Worker 监听 sync 事件
self.addEventListener('sync', (event: SyncEvent) => {
if (event.tag === 'retry-mutation') {
event.waitUntil(
(async () => {
const allClients = await self.clients.matchAll({ type: 'window' });
if (allClients.length === 0) return; // 无页面存活,放弃
// 通过 postMessage 把“请重试”指令发给 Redux
allClients[0].postMessage({ type: 'SW_RETRY_MUTATION' });
})()
);
}
});
- 根 Saga 监听 SW 消息并顺序重试
function* handleSwRetry() {
const queue: RetryQueueItem[] = yield select(state => state.retryQueue);
for (const item of queue) {
try {
yield call(fetch, `/api${item.endpoint}`, {
method: item.method,
headers: { 'Content-Type': 'application/json', 'Idempotency-Key': item.id },
body: JSON.stringify(item.payload)
});
yield put(removeFromQueue(item.id)); // 成功则清理
} catch (e) {
// 仍失败则保留队列,等待下次 sync
break;
}
}
}
yield takeEvery('SW_RETRY_MUTATION', handleSwRetry);
- 幂等保障
- 请求头带 Idempotency-Key(即队列 id);
- 服务端维护 key+userId 唯一索引,重复 key 直接返回 200 与原结果;
- 对账系统每日扫表,发现异常重试可回退。
拓展思考
- 如果用户杀掉浏览器进程,Background Sync 仍会在下次启动时触发,但队列依赖 IndexedDB 持久化,需把 retryQueue 从 Redux 状态迁到 IndexedDB,避免内存状态丢失。
- 对于多端登录场景,同一用户在不同设备产生冲突,可在 Idempotency-Key 里拼接 userId+deviceId,服务端按业务维度合并或提示冲突。
- 国内部分厂商 WebView 阉割 SW,需降级到“轮询网络+指数退避”方案,此时可封装统一的 RetryManager,向上暴露相同接口,保持 Redux 代码零改动。