Next.js应用中拉取库存数据存入localStorage未生效问题
核心问题定位
以下是导致数据无法写入的全部可复现问题点:
- 触发条件完全失效
- 当localStorage中不存在对应键时,
localStorage.getItem('inv')的返回值是null,并非undefined,原判断=== undefined永远无法满足,代码根本不会进入写入分支 - Next.js新版本已废弃
process.browser全局变量,该值在多数场景下为undefined,客户端环境判断直接失效 getInventory无有效返回值- 所有分页请求逻辑都写在
setTimeout的回调内部,回调内的return fullInventory属于setTimeout的私有作用域,不会作为getInventory的返回值向外传递 - 原for循环仅同步将所有setTimeout任务排入事件队列,未等待任务执行完成就直接结束函数执行,此时所有分页请求甚至还未触发,
await getInventory()最终拿到的返回值为undefined - 异步流程无等待机制
- 原写法中用setTimeout模拟请求间隔的逻辑没有被Promise包装,外层逻辑完全无法感知所有分页请求的完成时机
- 写入格式不符合localStorage规范
- localStorage仅支持字符串类型的存储内容,直接传入数组/对象会被隐式转换为无意义的
[object Object]字符串,即使流程跑通也无法获取有效库存数据
针对性修复方案
- 替换环境判断逻辑:用
typeof window !== 'undefined'替代已废弃的process.browser - 修正存在性判断:将键值判断从
=== undefined调整为=== null - 重构异步逻辑:将每个带延迟的分页请求封装为可被await的Promise,通过
Promise.all等待所有分页数据拉取完成后,再将拼接好的完整库存数组作为函数返回值 - 写入前对数据做序列化:用
JSON.stringify()将库存数组转为合法字符串后再存入localStorage,后续读取时通过JSON.parse()还原结构
修复后的核心代码
触发存储的逻辑调整为:
if (typeof window !== 'undefined' && localStorage.getItem('inv') === null) { const inv = await getInventory() localStorage.setItem('inv', JSON.stringify(inv)) }
getInventory 方法的核心逻辑调整为:
const getInventory = async () => { const token = await refreshToken() const header = { Authorization: `Bearer ${token}`, }; const queries = await getQueriesCount(); // 保留原有axios响应拦截逻辑 axios.interceptors.response.use(function (response) { return response; }, async function (error) { await new Promise(res => setTimeout(res, 2000)); const originalRequest = error.config; if (error.response.status === 401 && !originalRequest._retry) { originalRequest._retry = true; const refreshedHeader = await setHeader() axios.defaults.headers = refreshedHeader originalRequest.headers = refreshedHeader return Promise.resolve(axios(originalRequest)); } return Promise.reject(error); }); let fullInventory = []; // 为每个分页请求创建可等待的异步任务 const pageRequestTasks = Array.from({ length: queries }, async (_, index) => { // 保留原有逐页延迟的逻辑,避免请求频率过高 await new Promise(res => setTimeout(res, 2000 * index)); try { const res = await axios({ url: `${MyApi}/Item.json&offset=${index * 100}&customSku=!~,`, method: "get", headers: header, }); console.log(`adding items ${index * 100} through ${(index + 1) * 100}`); const items = res.data.Item; items?.length ? fullInventory = fullInventory.concat(items) : fullInventory.push(items); } catch (error) { console.error("We have a problem here: ", error.response); } }) // 等待所有分页请求完成后返回最终拼接的库存数据 await Promise.all(pageRequestTasks) return fullInventory; }
内容的提问来源于stack exchange,提问作者Darryl Morley
相关产品推荐
相关产品推荐

