微信小程序环境下 uni.createSelectorQuery API不能在nextTick下使用会报错

微信小程序环境下 uni.createSelectorQuery API不能在nextTick下使用会报错

项目属性
产品分类 uniapp/小程序/微信
PC开发环境操作系统 Windows
PC开发环境操作系统版本号 win10
HBuilderX类型 正式
HBuilderX版本号 4.57
第三方开发者工具版本号 RC 1.06.2503281
基础库版本号 3.8.0
项目创建方式 HBuilderX

操作步骤:

把uni.createSelectorQuery这个API放到nextTick里面一定报错

预期结果:

不会报错才对

实际结果:

UnhandledPromiseRejection: TypeError: Cannot read property '$scope' of null
14:48:11.879     at Object.newIn [as in] (http://127.0.0.1:34147/appservice/common/vendor.js:6368:19)
14:48:11.879     at Object.<anonymous> (http://127.0.0.1:34147/appservice/pages/index/index.js:17:65)

bug描述:

想要防止onMounted获取不到元素,把uni.createSelectorQuery这个API放在nextTick函数里面,导致了报错

mini.rar


2 回复

onMounted这个生命周期已经挂载完毕了,不用nextTick,或者你这样处理


这是一个微信小程序环境下uni.createSelectorQuery与nextTick结合使用时的常见问题。原因在于nextTick执行时组件可能还未完全挂载完成。

解决方法有以下几种:

  1. 直接使用setTimeout代替nextTick:
setTimeout(() => {
  uni.createSelectorQuery().select('#id').boundingClientRect()
}, 100)
  1. 在onReady生命周期中使用,而不是onMounted:
onReady() {
  uni.createSelectorQuery().select('#id').boundingClientRect()
}
  1. 如果必须使用nextTick,可以加一个组件存在判断:
nextTick(() => {
  if(this.$scope) {
    uni.createSelectorQuery().in(this).select('#id').boundingClientRect()
  }
})
回到顶部