问题简介

近期在开发一个菜单管理操作Array增加元素的时候出现一个循环引用的问题

问题代码段
Uncaught (in promise) TypeError: Converting circular structure to JSON --> starting at object with constructor 'Array' | index 0 -> object with constructor 'Object' --- property 'sub_button' closes the circle at JSON.stringify () at transformRequest (defaults.js?2822:51) at transform (transformData.js?4cd5:16) at Object.forEach (utils.js?7061:224) at transformData (transformData.js?4cd5:15) at dispatchRequest (dispatchRequest.js?c4bb:37)
1
2
3
4
5
6
7
8
9
10
11
const buttonIndex = this.buttons.indexOf(this.selectMenu);
const buttonElement = this.buttons[buttonIndex];
this.dialog.key = md5(new Date().toString());
//防止出现循环引用
this.dialog.sub_button = [];
buttonElement.sub_button.push(Object.assign({}, this.dialog));
this.$message({
type: 'success',
message: '一级菜单 <' + buttonElement.name + '> 下增加二级菜单 <' + this.dialog.name + '> 成功!'
});
this.dialogVisible = false;
##### 问题详细 ##### 代码写下来后按代码逻辑审阅是将出现符合心理预期的Array数组的,在数组以菜单展示时还未曾发现问题,在提交数据转换JSON格式就报错了,检查最后发现每一层子元素即sub_button[]下都有一个this.dialog数组,最后定位为循环引用导致
解决方式

push子元素时重置子元素中子元素例sub_button值,致其为空,即[]

1
2
3
4
5
...
this.dialog.key = md5(new Date().toString());
//防止出现循环引用
this.dialog.sub_button = [];
buttonElement.sub_button.push(Object.assign({}, this.dialog));