往session中存储vuex的数据,但是显示Uncaught TypeError: Converting circular structure to JSON
时间: 2023-08-11 17:10:55 浏览: 198
这个错误是因为你在尝试将一个包含循环引用的对象转换为 JSON 字符串。JSON 格式不支持循环引用,所以 JSON.stringify() 方法无法将其转换成字符串。
如果你想将包含循环引用的对象存储到 session 中,可以使用一个第三方库,比如 `flatted`,它可以将包含循环引用的对象转换成一个可序列化的对象。
安装 `flatted`:
```
npm install flatted
```
使用 `flatted` 序列化和反序列化对象:
```js
import flatted from 'flatted';
// 将包含循环引用的对象转换成字符串并存储到 session 中
const serializedData = flatted.stringify(yourObject);
sessionStorage.setItem('myData', serializedData);
// 从 session 中获取字符串并将其转换成对象
const serializedData = sessionStorage.getItem('myData');
const yourObject = flatted.parse(serializedData);
```
这样就可以将包含循环引用的对象存储到 session 中了。
相关问题
NoticeFlow.js:2727 Uncaught TypeError: Converting circular structure to JSON --> starting at object with constructor 'Window' --- property 'window' closes the circle at JSON.stringify (<anonymous>)
这个错误意味着您试图将包含循环引用的对象转换为 JSON 字符串,而 JSON.stringify() 方法无法处理循环引用。
在您的情况中,错误消息指出循环引用的起点是一个具有构造函数为 'Window' 的对象,并且循环引用的属性是 'window'。这是因为在浏览器环境中,'Window' 对象和 'window' 属性相互引用,导致循环引用。
要解决此问题,您需要确保在调用 JSON.stringify() 之前,从要转换的对象中删除循环引用的属性。
示例代码如下:
```javascript
var openedWindows = []; // 存储打开的标签页引用的数组
// 打开多个标签页
openedWindows.push(window.open('http://example.com'));
openedWindows.push(window.open('http://example2.com'));
openedWindows.push(window.open('http://example3.com'));
// 删除循环引用的属性
openedWindows.forEach(function(win) {
delete win.window;
});
// 转换为 JSON 字符串
var jsonString = JSON.stringify(openedWindows);
console.log(jsonString);
```
通过删除 'window' 属性,您可以避免循环引用,并且可以成功地将对象转换为 JSON 字符串。
TypeError: Converting circular structure to JSON
回答: TypeError: Converting circular structure to JSON是一个常见的错误,它发生在尝试使用JSON.stringify()方法将具有循环引用的对象转换为JSON字符串时。循环引用是指一个对象引用了自身,或者多个对象以循环方式相互引用。例如,当一个对象的某个属性指向了自身,或者多个对象相互引用时,就会出现循环引用。这种情况下,JSON.stringify()方法无法处理循环引用,因此会抛出该错误。\[1\]\[2\]\[3\]
#### 引用[.reference_title]
- *1* *3* [TypeError: Converting circular structure to JSON](https://blog.csdn.net/xiaojinglyd/article/details/103489651)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insertT0,239^v3^insert_chatgpt"}} ] [.reference_item]
- *2* [Uncaught TypeError: Converting circular structure to JSON](https://blog.csdn.net/brilliantSt/article/details/129685208)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insertT0,239^v3^insert_chatgpt"}} ] [.reference_item]
[ .reference_list ]
阅读全文