經典 React 生產環境錯誤:你部署了一個新 bundle,用戶在分頁中緩存了舊的 HTML,他們導航到一個路徑 → React.lazy() 嘗試導入在 CDN 上不再存在的 chunk → 空白螢幕.
控制台中的錯誤看起來像這樣:
動態導入模塊失敗:
https://cdn.example.com/assets/Page-abc123.js
用戶沒有任何出路,只能強制重新載入,而且大多數人不知道這點.
修復
一個全域的 error 監聽器,捕捉塊載入錯誤並使用緩存破壞參數強制重新載入頁面:
js
const CHUNK_ERROR_PATTERNS = [
/Loading chunk \d+ failed/i,
/Failed to fetch dynamically imported module/i,
/Loading CSS chunk .* failed/i,
/Importing a module script failed/i,
];
window.addEventListener('error', (e) => {
const msg = e?.message || '';
if (CHUNK_ERROR_PATTERNS.some(rx => rx.test(msg))) {
const url = new URL(window.location.href);
url.searchParams.set('_r', String(Date.now()));
window.location.replace(url.toString());
}
});
Why each part matters:
Multiple patterns: different browsers throw different messages. Safari uses "Importing a module script failed", Chrome uses "Failed to fetch dynamically imported module", older Webpack builds use "Loading chunk N failed".
Case insensitive: some browsers capitalize, some don't.
Cache-bust param: ?_r=<timestamp> forces fresh index.html, which has the new chunk hashes.
replace() not assign(): doesn't add a history entry, so back button works.
Gotchas
This catches unhandledrejection too if the lazy import throws inside a promise. Add a second listener if you see misses.
Don't trigger reload more than once: add a flag to avoid loops on a network outage.
Test it: deploy a new build, open the old tab, navigate. Should auto-recover.
It's 15 lines but saved me a real percentage of users abandoning the app post-deploy.











