12451 b553c4e519 feat: API 统一 + 设备详情补全 + H5 导航优化
- API 路由统一: 移除 /api/h5/,统一 /api/pms/ 入口
- 二进制改名: api-server -> pms-api(与服务名一致)
- nginx: 合并 /api/ + /pms/api/ 为 /api/pms/
- 新增 docs/API.md 接口文档
- 后端: CabinetDetail 增加 rssi/pow_fail/address/soc 等字段
- Redis 管道批量读取仓体实时数据(SOC/电压/电流/功率)
- DB: 所有 TIMESTAMP 列改为 DATETIME(修复类型不匹配)
- 用户管理: 新增创建时间/修改时间列,状态改用 Switch
- 角色管理/用户管理: 操作按钮改为图标
- PC 设备详情: 基本信息补全 RSSI/ICCID/电源/地址
- PC 卡片: 通道统计改用 Lucide 图标,颜色统一
- PC 二维码: canvas 渲染,含编号文字,支持右键下载
- H5: 按 uni-app 规范修正导航(navigateTo 替代 reLaunch)
- H5: 详情页加返回导航条
- H5: 扫码支持摄像头(jsQR)+ ?id= 参数
- H5: 底部 tabBar 在所有页面常显
- H5: 首页统计改为 6 项(设备/通道/空闲/充电/充满/故障)
- H5: 下拉刷新 / 上拉加载
- 产品首页: 添加业务联系
- 文档: 清理过时文件,补充缺失规范章节
2026-07-04 04:03:02 +08:00

5.0 KiB

title, impact, impactDescription, type, tags
title impact impactDescription type tags
Provide Must Be Called Synchronously During Setup HIGH Calling provide() asynchronously or conditionally may fail silently or cause inconsistent injection behavior gotcha
vue3
provide-inject
composition-api
async
setup

Provide Must Be Called Synchronously During Setup

Impact: HIGH - The provide() function must be called synchronously during the component's setup() phase. Calling it asynchronously (inside callbacks, promises, or after await) will fail silently, and descendant components will not receive the provided value.

Task Checklist

  • Always call provide() at the top level of setup() or <script setup>
  • Never call provide() inside async callbacks or after await statements
  • For async data, provide a ref first, then update its value later
  • Use immediate provide() with reactive containers for dynamic data

The Gotcha: Async Provide Fails Silently

Wrong - Provide after async operation:

<script setup>
import { provide } from 'vue'

// WRONG: provide() called after await - will NOT work
onMounted(async () => {
  const userData = await fetchUser()
  provide('user', userData) // Silent failure!
})
</script>

Wrong - Provide inside callback:

<script setup>
import { provide } from 'vue'

// WRONG: provide() inside callback - will NOT work
setTimeout(() => {
  provide('config', { theme: 'dark' }) // Silent failure!
}, 0)
</script>

Wrong - Provide after await in setup:

<script setup>
import { provide } from 'vue'

const response = await fetch('/api/config')
const config = await response.json()

// WRONG: This is after an await, setup context may be lost
provide('config', config) // May not work reliably
</script>

Solution: Provide Synchronously, Update Async

Correct - Provide ref immediately, update later:

<script setup>
import { provide, ref, onMounted } from 'vue'

// Provide immediately with initial value
const user = ref(null)
const isLoading = ref(true)
const error = ref(null)

provide('userState', {
  user,
  isLoading,
  error
})

// Update the ref values asynchronously
onMounted(async () => {
  try {
    const userData = await fetchUser()
    user.value = userData
  } catch (e) {
    error.value = e
  } finally {
    isLoading.value = false
  }
})
</script>
<!-- Consumer component -->
<script setup>
import { inject } from 'vue'

const { user, isLoading, error } = inject('userState')
</script>

<template>
  <div v-if="isLoading">Loading...</div>
  <div v-else-if="error">Error: {{ error.message }}</div>
  <div v-else>Welcome, {{ user?.name }}</div>
</template>

Pattern: Async Data Provider

Create a reusable pattern for async-provided data:

<!-- AsyncDataProvider.vue -->
<script setup>
import { provide, ref, onMounted, watch } from 'vue'

const props = defineProps({
  fetchFn: {
    type: Function,
    required: true
  },
  provideKey: {
    type: [String, Symbol],
    required: true
  },
  immediate: {
    type: Boolean,
    default: true
  }
})

const data = ref(null)
const isLoading = ref(false)
const error = ref(null)

async function load() {
  isLoading.value = true
  error.value = null

  try {
    data.value = await props.fetchFn()
  } catch (e) {
    error.value = e
  } finally {
    isLoading.value = false
  }
}

// Provide synchronously
provide(props.provideKey, {
  data,
  isLoading,
  error,
  reload: load
})

// Fetch asynchronously
if (props.immediate) {
  onMounted(load)
}
</script>

<template>
  <slot />
</template>

Usage:

<template>
  <AsyncDataProvider
    :fetch-fn="() => api.getUser(userId)"
    provide-key="userData"
  >
    <UserProfile />
  </AsyncDataProvider>
</template>

Why This Happens

Vue's provide() relies on the current component instance context, which is only available synchronously during setup. After setup completes:

  1. The setup context is cleared
  2. provide() can't find the current instance
  3. The call fails silently (no error thrown)

Checking for Setup Context

You can verify if setup context is available:

import { getCurrentInstance } from 'vue'

function debugProvide(key, value) {
  const instance = getCurrentInstance()

  if (!instance) {
    console.error(
      `provide() called outside setup context. ` +
      `Key: ${String(key)}. This will fail silently.`
    )
    return
  }

  provide(key, value)
}

App-Level Provide (Exception)

app.provide() can be called anytime during app initialization:

// main.js
import { createApp } from 'vue'
import App from './App.vue'

const app = createApp(App)

// This works - app-level provide
app.provide('appConfig', { version: '1.0.0' })

// Even async is OK at app level before mount
fetchConfig().then(config => {
  app.provide('apiConfig', config)
  app.mount('#app')
})

But once the app is mounted, app.provide() should not be called.

Reference