← Back to list

用 Optional Chaining 避免 Cannot read property of undefined

我們在寫 Vue、Node.js 或串接 API 時,

Chiayu · 2026-06-08 09:29 · 0 claps · 2.3 min read
#javascript #js #optional-chaining #question-mark #軟體工程師
Open on Medium ↗
Wiki topics: CRY · Crypto & Web3 🌐 · Web Development

用 Optional Chaining 避免 Cannot read property of undefined

我們在寫 Vue、Node.js 或串接 API 時,

很常遇到這種錯誤

Cannot read properties of undefined

例如:

user.profile.name

但 API 還沒回來,

或是 profile 不存在,

程式就直接爆炸了。

這時候就很適合使用:

?.

也就是 Optional Chaining 可選串連運算子

真實開發情境

假設 API 回傳:

const user = {
  name: '小明'
};

現在需求是取得使用者的 profile 名稱

如果直接寫:

console.log(user.profile.name);

結果:

Cannot read properties of undefined

因為:

user.profile

根本不存在。

核心觀念

Optional Chaining 很像幫我先檢查資料存不存在。

如果存在:

  • 繼續往下取值

如果不存在

  • 直接回傳 undefined

不會讓程式爆錯。

語法:

物件?.欄位

例如:

user?.profile

文件怎麼看

MDN 文件:

MDN Optional Chaining 官方文件

文件會看到:

obj?.prop

意思其實就是:

如果 obj 存在
就取 prop

否則:

undefined

完整實作

沒有 Optional Chaining:

const user = {
  name: '小明'
};

console.log(user.profile.name);

結果:

Cannot read properties of undefined

使用 Optional Chaining:

const user = {
  name: '小明'
};

console.log(user?.profile?.name);

結果:

undefined

程式不會報錯。

常見卡點

很多人會寫:

user.profile?.name

但如果:

user

本身就不存在,

還是會報錯。

保險的寫法:

user?.profile?.name

每一層都檢查。

搭配 ??

const city =
  customer?.city ?? "Unknown";

如果:

customer = {
  city: "Taipei"
}

結果:

Taipei

如果:

customer = {}

結果:

Unknown

重點整理

語法:

obj?.property

作用資料存在才繼續往下取值

常見用途:

  • API 回傳資料
  • Vue Template 顯示資料
  • Pinia Store 狀態讀取
  • 巢狀物件存取

我的理解與思考

以前串接 API 時

常常資料沒回來

所以報錯,整個程式壞掉

現在這個方式可以更好防止

也可以更好找到問題

但還是要考慮好資料流的狀況喔!


메타데이터
post_id
39cd1f3333f8
slug
用-optional-chaining-避免-cannot-read-property-of-undefined-39cd1f3333f8
url
https://medium.com/@hotdanton08/%E7%94%A8-optional-chaining-%E9%81%BF%E5%85%8D-cannot-read-property-of-undefined-39cd1f3333f8
canonical_url
https://medium.com/@hotdanton08/%E7%94%A8-optional-chaining-%E9%81%BF%E5%85%8D-cannot-read-property-of-undefined-39cd1f3333f8
author_url
https://medium.com/@hotdanton08
status
ok
fetched_at
2026-06-09 22:10:26