charging-cabinet/software/h5-uniapp/agent/skills/vue-best-practices/reference/composition-api-script-setup-async-context.md
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.2 KiB

title, impact, impactDescription, type, tags
title impact impactDescription type tags
Top-Level await in script setup Preserves Component Context HIGH Misunderstanding async context causes lifecycle hooks and watchers to silently fail gotcha
vue3
composition-api
script-setup
async
await
suspense

Top-Level await in script setup Preserves Component Context

Impact: HIGH - In <script setup>, top-level await statements preserve component context (allowing lifecycle hooks and watchers after await), but this is a special case. Nested async functions or callbacks lose context, causing lifecycle hooks to silently fail.

Vue's compiler automatically injects context restoration after each top-level await in <script setup>. This doesn't apply to setup() function or nested async contexts.

Task Checklist

  • Understand that top-level await in <script setup> is specially handled
  • Never register lifecycle hooks in nested async functions
  • Use <Suspense> when using async <script setup> components
  • In regular setup(), never use await before lifecycle hook registration
  • Register hooks synchronously, then do async work inside them

Top-Level await Works (script setup only):

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

// This is TOP-LEVEL await - Vue compiler preserves context
const config = await fetchConfig()  // OK!

// These hooks work because Vue restored context
onMounted(() => {
  console.log('This will run!')  // Works
})

watch(someRef, () => {
  console.log('This will track!')  // Works
})

// Another top-level await - still OK
const data = await fetchData(config.apiUrl)  // OK!

// Still works after multiple awaits
onMounted(() => {
  console.log('This also runs!')  // Works
})
</script>

<!-- IMPORTANT: Parent must use Suspense -->
<template>
  <Suspense>
    <AsyncComponent />
  </Suspense>
</template>

Nested Async Breaks Context:

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

// WRONG: Nested async function - context lost after await
async function initializeData() {
  const config = await fetchConfig()

  // BUG: This hook will NOT be registered!
  // We're no longer in the synchronous setup context
  onMounted(() => {
    console.log('This will NEVER run!')  // Silent failure
  })

  // BUG: This watcher won't auto-dispose on unmount
  watch(someRef, () => {
    console.log('Memory leak - not cleaned up!')
  })
}

// Calling the async function
initializeData()  // Hooks inside won't work!

// WRONG: Callbacks also lose context
setTimeout(async () => {
  await delay(100)
  onMounted(() => {
    console.log('Never runs!')  // Silent failure
  })
}, 0)
</script>

Correct Patterns:

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

const data = ref(null)
const config = ref(null)

// CORRECT: Register hooks synchronously FIRST
onMounted(async () => {
  // Then do async work INSIDE the hook
  config.value = await fetchConfig()
  data.value = await fetchData(config.value.apiUrl)
})

// CORRECT: Watchers registered synchronously
watch(config, async (newConfig) => {
  if (newConfig) {
    data.value = await fetchData(newConfig.apiUrl)
  }
})

// Or use top-level await for initial data
const initialConfig = await fetchConfig()  // OK - top level
config.value = initialConfig

onMounted(() => {
  console.log('Works!')  // Context preserved by compiler
})
</script>

setup() Function (Not script setup):

// In regular setup(), await ALWAYS breaks context
export default {
  async setup() {
    const data = ref(null)

    // WRONG: Hooks after await won't register
    const config = await fetchConfig()

    onMounted(() => {
      console.log('Never runs!')  // Silent failure!
    })

    return { data }
  }
}

// CORRECT: Register hooks before any await
export default {
  async setup() {
    const data = ref(null)

    // Register hooks FIRST (synchronous)
    onMounted(async () => {
      const config = await fetchConfig()
      data.value = await fetchData(config)
    })

    // Now you can await if needed
    // But hooks must be registered before this point

    return { data }
  }
}

Why This Happens

// Vue tracks the "current component instance" during setup
// This is like a global variable that gets set and cleared

// During synchronous setup:
function setup() {
  currentInstance = this  // Vue sets this

  onMounted(cb)  // Uses currentInstance to register

  // After await, JavaScript resumes in a microtask
  await something()

  // currentInstance is now null or different!
  onMounted(cb)  // Can't find the instance - silently fails
}

// <script setup> compiler adds restoration:
// After each await, it injects: setCurrentInstance(savedInstance)

Suspense Requirement

<!-- When using async script setup, parent needs Suspense -->
<template>
  <Suspense>
    <!-- Async component with top-level await -->
    <AsyncChild />

    <!-- Optional: Loading state -->
    <template #fallback>
      <LoadingSpinner />
    </template>
  </Suspense>
</template>

Reference