You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修复TypeError: 无法读取未定义对象的属性'bigPoster'?

错误修正方案:TypeError: 无法读取未定义对象的属性'bigPoster'

错误根源

这个报错是因为moviesByGenre数组为空(某个分类下没有找到对应的电影),导致moviesByGenre[0]为undefined,尝试读取它的bigPoster属性时触发类型错误。

修正方案

方案1:过滤无电影的分类

如果业务不需要展示没有电影的分类,可以在生成集合时跳过这类分类:

async getCollections(): Promise<ICollection[]> {
    const genres = await this.getAll()
    const collections = await Promise.all(
        genres.map(async (genre) => {
            const moviesByGenre = await this.movieService.byGenres([genre._id])
            // 无电影则返回null,后续过滤
            if (!moviesByGenre.length) return null
            const result: ICollection = {
                _id: String(genre._id),
                title: genre.name,
                slug: genre.slug,
                image: moviesByGenre[0].bigPoster,
            }
            return result
        })
    )
    // 过滤掉空结果
    return collections.filter(Boolean) as ICollection[]
}

方案2:设置默认图片

如果需要保留所有分类,给无电影的分类设置默认海报:

async getCollections(): Promise<ICollection[]> {
    const genres = await this.getAll()
    const collections = await Promise.all(
        genres.map(async (genre) => {
            const moviesByGenre = await this.movieService.byGenres([genre._id])
            const result: ICollection = {
                _id: String(genre._id),
                title: genre.name,
                slug: genre.slug,
                // 用可选链避免报错,空值合并指定默认图路径
                image: moviesByGenre[0]?.bigPoster ?? '/assets/default-poster.jpg',
            }
            return result
        })
    )
    return collections
}

方案3:抛出明确错误(强制分类有电影)

如果业务要求每个分类必须关联电影,可抛出明确错误便于排查:

async getCollections(): Promise<ICollection[]> {
    const genres = await this.getAll()
    const collections = await Promise.all(
        genres.map(async (genre) => {
            const moviesByGenre = await this.movieService.byGenres([genre._id])
            if (!moviesByGenre.length) {
                throw new Error(`分类「${genre.name}」(ID: ${genre._id}) 未找到关联电影`)
            }
            const result: ICollection = {
                _id: String(genre._id),
                title: genre.name,
                slug: genre.slug,
                image: moviesByGenre[0].bigPoster,
            }
            return result
        })
    )
    return collections
}

方案选择

  • 方案1:适合不需要空分类展示的场景
  • 方案2:适合需要保留所有分类的场景
  • 方案3:适合业务逻辑强制分类必须有电影的场景

内容的提问来源于stack exchange,提问作者Zabor

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.22 04:22:48