MeWrite Docs

Vue: Cannot read property of undefined

Vue.jsでundefinedのプロパティにアクセスしようとした際のエラー

概要

Vue.jsでコンポーネントのデータやpropsがundefinedの状態でプロパティにアクセスしようとした場合に発生するエラーです。

エラーメッセージ

TypeError: Cannot read properties of undefined (reading 'name')

原因

  1. 非同期データの初期状態: APIからのデータ取得前にアクセス
  2. propsが未定義: 親コンポーネントからpropsが渡されていない
  3. ネストしたオブジェクトへのアクセス: 中間のオブジェクトがundefined

解決策

1. オプショナルチェイニングを使用

1
2
3
<template>
  <div>{{ user?.profile?.name }}</div>
</template>

2. v-if でガード

1
2
3
4
5
6
<template>
  <div v-if="user">
    {{ user.name }}
  </div>
  <div v-else>Loading...</div>
</template>

3. データの初期値を設定

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
<script setup>
import { ref } from 'vue'

const user = ref({
  name: '',
  profile: {
    bio: ''
  }
})
</script>

4. computed でデフォルト値

1
2
3
4
5
6
7
<script setup>
import { computed } from 'vue'

const userName = computed(() => {
  return user.value?.name ?? 'Guest'
})
</script>

5. props のデフォルト値

1
2
3
4
5
6
7
8
<script setup>
const props = defineProps({
  user: {
    type: Object,
    default: () => ({ name: '', email: '' })
  }
})
</script>

6. watch でデータ変更を監視

1
2
3
4
5
6
7
8
9
<script setup>
import { watch } from 'vue'

watch(() => props.user, (newUser) => {
  if (newUser) {
    // データが利用可能になった後の処理
  }
}, { immediate: true })
</script>

よくある間違い

  • createdフック内でDOMにアクセス(mountedを使うべき)
  • 非同期処理の完了前にデータを使用
  • リアクティブでないオブジェクトのプロパティ変更

Vue.js の他のエラー

最終更新: 2025-12-09