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

React Native Expo项目JSON.stringify循环结构序列化错误求助

问题:React Native Expo项目JSON序列化循环引用错误及后续导航问题

我在React Native Expo项目里遇到了这个错误:

TypeError: JSON.stringify cannot serialize cyclic structures. stringify@[native code]

尝试用json-stringify-safe库替换JSON.stringify,把请求体改成body: jsonStringifySafe(MessageData)后,又出现了react-navigation相关的错误,求帮忙解决。

前端代码

const SendMessage = async () => {
    const MessageData = {
        message: currentmessage,
        RoomId: roomid,
        SenderId: mydata._id,
        RecieverId: otheruser[0]._id
    };
    fetch('http://10.0.2.2:3000/saveMessage', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify(MessageData),
    })
        .then(res => res.json())
        .then(data => {
            if (data.message === "Message Saved!") {
                console.log("Message Saved!");
                setCurrentMessage('');
            } else {
                alert("Please, Try Again");
            }
        });
};

后端代码

router.post("/saveMessage", async (req, res) => {
    const { SenderId, RecieverId, message, RoomId } = req.body;

    try {
        const NewMessage = new Message({
            SenderId,
            RecieverId,
            message,
            RoomId
        })
        await NewMessage.save();
        res.send("Message Saved!")
    }
    catch (err) {
        console.log('error while saving message', err);
        res.status(422).send(err.message);
    }
})

解决方法

1. 根治循环引用问题

你定义的MessageData表面上是基础值,但currentmessage、roomid、mydata._id或otheruser[0]._id可能携带了循环引用的对象(比如mydata是包含自身引用的复杂对象,或是React组件实例、导航上下文这类带循环引用的结构)。

直接提取原始值,避免引用对象属性:

const MessageData = {
    message: String(currentmessage), // 强制转成字符串,剥离对象引用
    RoomId: String(roomid),
    SenderId: String(mydata._id),
    RecieverId: String(otheruser[0]._id)
};

这样所有字段都是原始字符串类型,不会触发循环序列化错误。

2. 修复后端返回格式问题

后端用res.send("Message Saved!")返回的是纯文本,但前端调用了res.json()解析,这会导致解析失败,进而触发后续的错误逻辑(比如data.message不存在,进入alert分支,甚至影响导航状态)。

把后端返回改成JSON格式:

// 替换原res.send("Message Saved!")
res.json({ message: "Message Saved!" })

3. 放弃json-stringify-safe的原因

这个库会把循环引用的部分替换成[Circular]标记,导致后端接收到的请求体格式不符合预期,无法正确解析字段,请求失败后可能触发前端的导航状态异常,所以优先解决根源问题,不要用兼容库绕过。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 04:55:23