渲染CourseDescriptionPageComponent时触发TypeError:无法读取undefined的'title'属性
Root Cause
The error pops up because your component tries to access properties like course.title before the course data finishes loading from the store. Here's the breakdown:
- When the component first renders, the
createdhook kicks off the asyncloadCourseDetailsaction, but this takes time to complete. - The computed
courseproperty returnsthis.$store.state.courseDetails[this.id], which isundefineduntil the async operation resolves. - Your template is likely attempting to access
course.titleimmediately, leading to the TypeError.
Solution 1: Guard Template Access with v-if
Wrap course-dependent template sections with a v-if check to ensure the data exists before rendering:
<template> <div v-if="course"> <h1>{{ course.title }}</h1> <!-- Your course components --> <CourseCover :course="course" /> <WhyJoin :course="course" /> <CourseStructure :course="course" /> </div> <div v-else> <!-- Optional loading state --> <p>Loading course details...</p> </div> </template>
This prevents the template from trying to access properties on an undefined value.
Solution 2: Use Optional Chaining (Vue 3 or Babel-enabled Vue 2)
If you’re on Vue 3 or have Babel set up to support optional chaining, you can safely access nested properties without explicit checks:
<template> <h1>{{ course?.title }}</h1> <CourseCover :course="course" /> </template>
The ?. operator returns undefined instead of throwing an error if course is null/undefined.
Solution 3: Fallback to Empty Object in Computed Property
Update your computed course property to return an empty object when the course isn’t found. This avoids undefined errors when accessing properties:
computed: { course () { return this.$store.state.courseDetails[this.id] || {} } }
Now course.title will just return undefined instead of crashing, and you can add default text if needed (e.g., {{ course.title || 'Untitled Course' }}).
Solution 4: Handle Loading State Explicitly
Use your existing hasDetails flag to manage the loading state, and add error handling for failed requests:
<template> <div v-if="hasDetails"> <h1>{{ course.title }}</h1> <!-- Course components --> </div> <div v-else> Loading course details... </div> </template>
Update the created hook to handle errors:
created () { this.$store.dispatch('loadCourseDetails', this.id) .then(() => { this.hasDetails = true }) .catch(err => { console.error('Failed to load course:', err) // Optionally show an error message to users }) }
内容的提问来源于stack exchange,提问作者aditya tandon

