解决 TypeError: Converting circular structure to JSON --> starting at object with

557 阅读1分钟

前段时间在某前端周刊看到一个库,是用来解决前端 JSON.stringify方法去转化成字符串报错的问题,当时心里想,这么奇葩和小众的问题,谁会遇到呢。

万万没想到,第二天,就在项目的控制台中发现了眼熟的error,没错,就是前一天刚看到的哪个。还好我当时收藏了。 这让我想起来最初学前端的时候,看到张鑫旭大佬的博客,看着各种奇怪的案例,还在想,这一般人遇不到这种问题吧。后来等我遇到的时候,立马眼前想到的就是大佬的博文。

遇不到,说明遇到的场景太少,不够复杂。

话不多说,报错内容如下:

Uncaught (in promise) TypeError: Converting circular structure to JSON --> starting at object with constructor 'Object' | property 'cfg' -> object with constructor 'Object' | property 'children' -> object with constructor 'Object' | ... | property 'cfg' -> object with constructor 'Object' --- property 'parent' closes the circle at JSON.stringify (<anonymous>)

image.png

什么原因呢?对象中有对自身的循环引用

使用第三方库即可

https://github.com/sindresorhus/safe-stringify

使用方法如下:

import safeStringify from 'safe-stringify';

const foo = {a: true};
foo.b = foo;

console.log(safeStringify(foo));
//=> '{"a":true,"b":"[Circular]"}'

console.log(JSON.stringify(foo));
//=> TypeError: Converting circular structure to JSON

日常多看看,遇到有用的多收藏还是有好处的。