【问题标题】:TypeError: JSON.stringify cannot serialize cyclic structures. stringify@[native code]TypeError: JSON.stringify 无法序列化循环结构。 stringify@[本机代码]
【发布时间】:2023-02-01 17:28:11
【问题描述】:

在我的 React Native Expo 项目中,我遇到了一个错误,上面写着“TypeError: JSON.stringify cannot serialize cyclic structures.stringify@[native code]” 谁能帮我解决这个问题?我尝试使用一个名为“json-stringify-safe”的库,但在像“body: jsonStringifySafe(MessageData)”这样使用它之后,它给我 react-navigation error 谁能帮我解决这个错误?

   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");
                }
            });
    };

【问题讨论】:

    标签: javascript reactjs react-native


    【解决方案1】:

    该错误告诉您,您在 MessageData(或其后代)上拥有一个直接或间接指向他们自己的属性。例如:

    const parent = { children: [] };
    const child = { parent };
    parent.children.push(child);
    

    此时,parent 指的是child,后者指的是parent。如果你对它们中的任何一个(直接或间接)做了 JSON.stringify,你会得到这个错误,因为 JSON 不能表示循环结构:

    const parent = { children: [] };
    const child = { parent };
    parent.children.push(child);
    console.log(JSON.stringify(parent));

    因此,您必须查看MessageData 及其引用的对象才能找出循环所在的位置。请注意,它可能非常深入:

    const parent = { children: [] };
    const child = { parent };
    parent.children.push(child);
    
    const zero = {
        one: {
            two: {
                three: {
                    parent
                },
            },
        },
    };
    
    console.log(JSON.stringify(zero));

    一些 JavaScript 引擎为您提供了比其他引擎更多的关于循环结构的信息。例如,以下是 V8(Chromium 浏览器和 Node.js 使用的引擎)对上述内容的描述:

    js:26 未捕获类型错误:将循环结构转换为 JSON
        --> 从带有构造函数“Object”的对象开始
        |属性 'children' -> 带有构造函数 'Array' 的对象
        |索引 0 -> 具有构造函数“对象”的对象
        --- 属性 'parent' 关闭圆圈
        在 JSON.stringify()
        在 js:26:18

    这提供了很多信息,比您在问题中引用的内容更多。因此,如果您还没有重现该问题,您可以尝试使用 Chromium 浏览器,希望它能为您提供有关循环所在位置的更多详细信息。

    【讨论】:

      猜你喜欢
      • 2017-07-05
      • 2013-11-21
      • 2015-12-26
      • 2016-01-22
      • 1970-01-01
      • 2013-05-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多