当应用从后台唤醒时,如何自动重试失败的 Mutation?
解读
国内移动端场景(尤其是微信小程序、React-Native 壳内 H5)有一个共同痛点:用户把 App 切到后台再回来时,网络状态可能从“不可用”瞬间恢复,但上次因 4xx/5xx 或断网而失败的 Mutation 仍然“躺在失败队列里”。面试官问“自动重试”并不是让你简单调 retryLink,而是考察三件事:
- 如何感知“从后台唤醒”这一国产机型碎片化事件;
- 如何把 Mutation 失败“持久化”下来,防止杀进程后丢失;
- 如何在唤醒瞬间按业务优先级幂等地重放,且不给服务端造成脏写。
知识点
- AppState / VisibilityChange / PageShow:Web 侧用
document.visibilityState或pageshow事件;小程序侧用onShow;RN 用AppState。 - Mutation 幂等键:国内接口通常要求
idempotency-key放在 Header,或业务字段_requestId做去重。 - Apollo Link 组合:
retryLink(指数退避)+onErrorLink(错误收集)+persistLink(IndexedDB/微信 Storage 持久化队列)。 - 队列持久化:失败 Mutation 序列化为
{ operation, variables, context, idempotencyKey, retryAfter },存 IndexedDB(Web)或微信 Storage(小程序),上限 50 条,防爆库。 - 重放策略:唤醒后先走
client.reFetchObservableQueries()恢复 Query,再按retryAfter时间戳升序重放 Mutation;若服务端返回 409 Conflict(幂等命中)则直接标记成功。 - 离线插件:Apollo 3.7+ 的
@apollo/client/link/offline在国内需要二次封装,因为微信 WebView 不支持 Background Sync,必须自己用visibilitychange触发。 - 错误分级:网络层错误(ERR_NETWORK)立即重试;业务 4xx 只重试 409/429,其余落日志不上报;5xx 走指数退避,最多 3 次。
- 内存与性能:重试队列用
p-queue限并发 1,防止瞬间 20 条 Mutation 把小程序 2M 内存打满;同时带AbortController,超过 10 秒未响应则丢弃并提示用户。
答案
- 监听生命周期
Web 侧:
document.addEventListener('visibilitychange', () => {
if (!document.hidden) retryOfflineMutations();
});
小程序侧:
Page({
onShow() { retryOfflineMutations(); }
});
- 封装离线队列
const offlineLink = new ApolloLink((operation, forward) => {
return forward(operation).pipe(
catchError(err => {
if (isNetworkError(err)) {
queue.add({
...operation.toKey(),
idempotencyKey: uuid(),
retryAfter: Date.now()
});
}
return throwError(err);
})
);
});
- 持久化
const persistQueue = {
async add(item) {
const arr = JSON.parse(await wx.getStorageSync('apollo:queue') || '[]');
arr.push(item);
await wx.setStorageSync('apollo:queue', JSON.stringify(arr.slice(-50)));
},
async drain() {
const arr = JSON.parse(await wx.getStorageSync('apollo:queue') || '[]');
wx.removeStorageSync('apollo:queue');
return arr;
}
};
- 唤醒重放
async function retryOfflineMutations() {
const list = await persistQueue.drain();
for (const item of list) {
await client.mutate({
mutation: gql(item.query),
variables: item.variables,
context: {
headers: {
'idempotency-key': item.idempotencyKey
}
}
}).catch(() => {
// 仍失败则重新入队
persistQueue.add(item);
});
}
}
- 退避与并发控制
用p-queue限流,并在retryLink中配置delay: { initial: 300, max: 5000, jitter: true },防止国内弱网瞬间洪峰。
拓展思考
- 如果业务要求“只重试用户最后一次提交”,可把队列换成环形缓冲区,保留最近一条 Mutation,其余丢弃,降低小程序存储压力。
- 对金融场景,重试前需重新拉取
refreshToken,防止唤醒后 Token 过期造成 401;此时把 Mutation 队列与登录守卫串成 Promise 链,确保先刷新再重放。 - 在 React-Native 0.72 背景任务新 API 里,可配合
react-native-background-fetch做“静默重试”,但国内安卓厂商会冻结后台网络,实际只能依赖“回到前台”事件,因此方案与 Web 对齐即可。