在开发uniapp项目中,有时运行在微信小程序上测试会报错,报错信息是:[Vue warn]: Property or method “toJSON” is not defined on the instance but referenced during render. Make sure that this property is reactive, either in the data option, or for class-based components, by initializing the property

1. 问题呈现

微信小程序开发工具上运行时报错,是这样的,如下截图所示
在这里插入图片描述

2. 定位问题

网上查了一下报错信息,大概知道解释的意思,但是没有用,先用排除法,把之前认为写过的可能有导致问题的代码注释掉,再运行试试,最后发现,应该是这里引起的,源代码如下

export default {
	data() {
		return {
			//...
			myComponent:null,
		};
	},
	onReady() {
		
	},
	mounted() {
		this.$nextTick(()=>{
			console.log('myComponent',this.$refs.myComponent);//测试打印正常
			//this.myComponent = this.$refs.myComponent;
		})
	},
}

💡 将上面那一行去掉注释后,运行会导致错误[Vue warn]: Property or method "toJSON" is not defined on the ...

3. 问题解决

经过各种猜测,最后有一个可行的方法试了,发现只要注释某一行即可,代码如下

export default {
	data() {
		return {
			//...
			//myComponent:null,
		};
	},
	onReady() {
		
	},
	mounted() {
		this.$nextTick(()=>{
			console.log('myComponent',this.$refs.myComponent);//测试打印正常
			this.myComponent = this.$refs.myComponent;
		})
	},
}

又发现一个🕷,为什么会导致这样的问题呢,且容我卖个关子…😛,这是绑定变量引起的,是Vue的特征,可有明白❓

Logo

AtomGit 是由开放原子开源基金会联合 CSDN 等生态伙伴共同推出的新一代开源与人工智能协作平台。平台坚持“开放、中立、公益”的理念,把代码托管、模型共享、数据集托管、智能体开发体验和算力服务整合在一起,为开发者提供从开发、训练到部署的一站式体验。

更多推荐