You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

NextJS映射Strapi数据报错:Invalid value used as weak map key

NextJS映射Strapi数据时出现「Invalid value used as weak map key」错误的解决办法

问题根源

这个错误是Next.js Server Components在序列化数据时遇到了无法被WeakMap处理的异常值,结合你新增Strapi数据后才出问题的情况,核心原因是:

  • 新增的某条数据里,关联字段(如saddle_type、order_status)为空或未正确关联,导致你访问data.attributes时拿到了null/undefined这类无法序列化的值
  • 日期处理逻辑错误:DateTime.now()不需要传参数,你传入时间字符串的用法完全错误,生成了异常对象

修复步骤

1. 给嵌套属性加空值保护

所有嵌套访问的字段都加上可选链操作符?.,避免空值导致的序列化失败,同时给默认值兜底:

{tempOrders.map((entry) => (
    <DataEntry
        key={entry.id.toString()}
        id={entry.id}
        saddlename={entry.attributes.saddle_type?.data?.attributes?.Name || '无'}
        seatsize={entry.attributes.order_attributes?.SeatSize || '无'}
        colour={entry.attributes.order_attributes?.Colour || '无'}
        status={entry.attributes.order_status?.data?.attributes?.status_name || '无'}
        customer={entry.attributes.order_attributes?.Customer || '无'}
        createdAt={entry.attributes.createdAt ? DateTime.fromISO(entry.attributes.createdAt).toFormat('dd/MM/yyyy') : '无'}
        updatedAt={entry.attributes.updatedAt ? DateTime.fromISO(entry.attributes.updatedAt).toFormat('dd/MM/yyyy') : '无'}
        passer={entry.attributes.saddle_fitter_id?.data?.attributes?.username || '无'}
    />
))}

2. 修正日期解析逻辑

把错误的DateTime.now(entry.attributes.createdAt)改成DateTime.fromISO(entry.attributes.createdAt)——DateTime.now()是获取当前时间,解析Strapi返回的ISO时间字符串必须用fromISO。

3. 排查新增的Strapi数据

直接去Strapi后台检查新增的那条订单:

  • 确认saddle_type、order_status、saddle_fitter_id这些关联字段都正确选择了对应的数据,有没有漏选的情况
  • 检查order_attributes里的SeatSize、Colour、Customer是否都填了值,有没有空字段

4. 可选:提前清洗数据

如果Strapi返回的数据结构经常不稳定,在获取数据后先做一层清洗,给所有可能为空的字段加默认值:

// 示例:在获取数据的Server Component或getServerSideProps中处理
const cleanedOrders = tempOrders.map(order => ({
    ...order,
    attributes: {
        ...order.attributes,
        saddle_type: order.attributes.saddle_type || { data: { attributes: { Name: '无' } } },
        order_status: order.attributes.order_status || { data: { attributes: { status_name: '无' } } },
        saddle_fitter_id: order.attributes.saddle_fitter_id || { data: { attributes: { username: '无' } } },
        order_attributes: order.attributes.order_attributes || { SeatSize: '无', Colour: '无', Customer: '无' }
    }
}));

快速定位问题的方法

先把映射代码注释掉,只渲染表头,确认页面正常后,再逐个恢复DataEntry的属性,或者单独渲染新增的那条数据,就能快速找到是哪个字段导致的序列化异常。

内容的提问来源于stack exchange,提问作者Michiel Verbeke

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 04:46:11