�鸿蒙报错速查:arkts-no-with 禁用 with 语句,用了就炸,根因 + 真解法
报错原文
ERROR: 10505001 ArkTS Compiler Error Error Message: "with" statement is not supported (arkts-no-with). At File: xxx.ets:N:N常伴生报错:
Error Message: 'with' statements are not allowed in strict mode. Error Message: The 'with' statement is not supported. All symbols in a 'with' block will have type 'any'.报错触发场景
你写鸿蒙 ArkTS 时,用with语句简化对象属性访问就炸:
// ❌ 报错写法 interface Point { x: number y: number } const p: Point = { x: 100, y: 200 } as Point with (p) { const sum: number = x + y ← arkts-no-with 报错,x/y 作用域不明 console.info(`${x}, ${y}`) ← arkts-no-with 报错 }根因
鸿蒙 ArkTS禁用with语句——这是跟前端 JS 最大的差异。JS 里with (obj) { ... }是把对象属性注入作用域省写obj.,ArkTS 里直接报错。
ArkTS 这么设计的原因:with破坏作用域清晰性——with (p) { x + y }里的x/y可能是p.x/p.y也可能是外层作用域的x/y,编译器静态分析不了。ArkTS 要求编译期消除一切歧义,禁用with保持作用域清晰。
真解法
一种解法:直接obj.attr访问替代 with
// ✅ 正解:直接 obj.attr 访问替代 with interface Point { x: number y: number } const p: Point = { x: 100, y: 200 } as Point const sum: number = p.x + p.y ← 直接 p.x/p.y 访问 console.info(`${p.x}, ${p.y}`)关键点:with的唯一用途是省写obj.—— ArkTS 里老老实实写obj.attr,作用域清晰,编译器静态分析得了。
高频踩坑场景
场景 1:省写对象属性
// ❌ 报错 with (p) { const sum = x + y } // ✅ 正解(直接 obj.attr) const sum = p.x + p.y场景 2:嵌套对象省写
// ❌ 报错 with (config.theme) { primary = '#FF0000' secondary = '#00FF00' } // ✅ 正解(直接路径访问) config.theme.primary = '#FF0000' config.theme.secondary = '#00FF00' // 或解构取局部变量 const { primary, secondary } = config.theme场景 3:动态对象省写
// ❌ 报错 with (obj) { console.info(key) } // ✅ 正解(直接访问或 Object.keys) for (const key of Object.keys(obj)) { console.info(obj[key]) }场景 4:API 回传对象省写
// ❌ 报错 const res = await api() with (res) { if (code === 0) { console.info(data.name) } } // ✅ 正解(直接访问) const res = await api() as Resp if (res.code === 0) { console.info(res.data.name) } // 或解构 const { code, data } = res if (code === 0) { console.info(data.name) }一句话速查
arkts-no-with → with 禁用,直接
obj.attr访问或解构const { x, y } = obj替代
跟前端 JS 的差异
| 写法 | JS | ArkTS |
|---|---|---|
with (obj) { x + y } | ✅(非严格模式) | ❌ 报错 |
obj.x + obj.y | ✅ | ✅ |
const { x, y } = obj; x + y | ✅ | ✅ |
前端转鸿蒙最容易踩这个坑——JS 里with是省写属性逃生阀(严格模式也禁),ArkTS 里直接编译炸。新项目从一开始就养成「禁用 with,直接 obj.attr 或解构」的习惯,避坑。
with 替代速查表
| 替代方案 | 适用场景 | 写法示例 |
|---|---|---|
直接obj.attr | 单次访问 | p.x + p.y |
| 解构取局部变量 | 多次访问同对象 | const { x, y } = p; x + y |
| Object.keys 遍历 | 动态对象 | Object.keys(obj) |
铁律:ArkTS 里搜不到with语句——遇到「要省写 obj.」就直接obj.attr或解构,别想 with。
完整代码仓库
本文所有正解写法都已托管到AtomGit:
🔗仓库地址:https://atomgit.com/JaneConan/arkui-bug-no-with
仓库包含:
- 四种高频踩坑场景的 ❌ 报错写法 + ✅ 正解写法对照
- 直接访问 / 解构 / Object.keys 三种替代方案示范
- 可直接用 DevEco Studio 打开参考
作者:JaneConan 仓库:https://atomgit.com/JaneConan/arkui-bug-no-with 协议:Apache-2.0,随便用,别告我
