有时候使用JSON.stringify()时会报这个错:
header.vue:92 Uncaught (in promise) TypeError: Converting circular structure to JSON
--> starting at object with constructor 'd'
| property '_readableState' -> object with constructor 'b'
| property 'pipes' -> object with constructor 'i'
| property '_readableState' -> object with constructor 'b'
--- property 'pipes' closes the circle
at JSON.stringify (<anonymous>)
at
解决办法:
// 由于json.stringify嵌套循环导致报错的解决函数,obj是要stringify的对象
const circularSafeStringify = (obj) => {
const cache = new Set();
return JSON.stringify(obj, (key, value) => {
if (typeof value === "object" && value !== null) {
if (cache.has(value)) {
// 当前对象已经存在于缓存中,说明存在循环引用,返回占位符或其他处理方式
return "[Circular Reference]";
}
cache.add(value);
}
return value;
});
}