TypeError: Converting circular structure to JSON
--> starting at object with constructor 'ComputedRefImpl'
| property 'effect' -> object with constructor 'ReactiveEffect'
--- property 'computed' closes the circle
at JSON.stringify (<anonymous>)
at parseValue (buildURL.js:51:20)
at Object.forEach (utils.js:270:10)
at serialize (buildURL.js:47:13)
at Object.forEach (utils.js:276:12)
at buildURL (buildURL.js:36:11)
at dispatchXhrRequest (xhr.js:46:47)
at new Promise (<anonymous>)
at xhrAdapter (xhr.js:16:10)
at dispatchRequest (dispatchRequest.js:58:10)
这样的报错,可能是在ref声明的响应式对象中,某些属性的值使用了计算属性,如:
const curPage = ref(1);
const offsetValue = computed(() => (curPage.value - 1) * 30),
hotParams = ref({
cateId: id,
limit: 30,
offset: offsetValue
});
将响应式对象改为使用reactive即可。
const curPage = ref(1);
const offsetValue = computed(() => (curPage.value - 1) * 30),
hotParams = reactive({
cateId: id,
limit: 30,
offset: offsetValue
});
分析:
报错看起来是因为computed属性造成循环引用,而无法将数据结构转换为JSON字符串造成的。其中ref在声明响应式时,若传入的参数是一个对象,则会调用reactive api创建代理对象然后返回。
和响应式对象的属性类似,ref 的 .value 属性也是响应式的。同时,当值为对象类型时,会用 reactive() 自动转换它的.value。
但是从数据结构上看,并没有数据的循环引用,而解决的办法也不是解除循环引用,而是显式使用reactive声明对象,所以可能是ref声明响应式的时候会在一个集合中做记录,而offsetValue计算属性引用的数据curPage也在那个集合中,所以导致认为有循环引用。
请问大家有需要过没有显式使用JSON.Stringfy,但是提醒有循环引用的情况吗?