【问题标题】:Error of "Cannot use 'in' operator to search for '0'", which doesn't occur on localhost“Cannot use 'in' operator to search '0'”的错误,在 localhost 上不会发生
【发布时间】:2020-08-17 06:46:00
【问题描述】:

我的项目在https://immense-refuge-12167.herokuapp.com/
如果我登录(邮箱:a@a.com,密码:11111111,或先注册后登录),然后点击左上角的“浏览器”按钮,控制台会出现如下错误: TypeError: Cannot use 'in' operator to search for '0'

它只发生在 Heroku 上,而不是 localhost。

发生错误的代码是:

      async mounted() {
        if(this.$store.state.isUserLoggedIn){
          const bookmarksOfThisUser = (await api.getAllBookmarks(this.$store.state.user.id)).data;
          if(bookmarksOfThisUser.length != 0 && !!bookmarksOfThisUser){
            for(var bookmark in bookmarksOfThisUser){
              const song = (await api.getASong(bookmarksOfThisUser[bookmark]['songId'])).data;
              this.bookmarks.push(song)
            }
          }
        }
      },

我意识到这可能是因为bookmarksOfThisUser的长度为0,所以我使用if(bookmarksOfThisUser.length != 0 && !!bookmarksOfThisUser)来防止它,但错误仍然发生。
mounted函数用于填充数据bookmarks,默认为空数组。使用此数据的元素是v-data-table,如下所示。

        <v-data-table
          :headers="headers"
          :items="bookmarks"
          :items-per-page="5"
          class="elevation-1"
          v-if="this.bookmarks.length != 0"
        >
          <template v-slot:item.action="item">
            <v-btn class="primary" small v-bind:to="{name: 'viewSong', params:{
            songId: item.item.id
            }}">View</v-btn>
          </template>
        </v-data-table>

我还用v-if检查了它的长度,但错误仍然发生......
谁能给我一些关于我做错了什么的提示?为什么它只发生在 Heroku 而不是 localhost 上?

谢谢!

【问题讨论】:

  • bookmarksOfThisUser 应该是一个对象而不是一个数组,所以 bookmarksOfThisUser.length != 0 没有任何意义。而是做if ( Object.keys(bookmarksOfThisUser).length )
  • 你还加载了 html 内容https://immense-refuge-12167.herokuapp.com/allBookmarks?userId=2
  • @NikosM.Sry 但错误仍然存​​在。请查看这篇文章中的 heroku 链接。登录然后转到“浏览器”,错误将显示在控制台中。我已经按照您的指示修改了我的代码并将其推送到 Heroku
  • 显然,我指的是错误的条件,但您的问题不会发生,因为bookmarksOfThisUser 的长度为零,这是另一个原因。我只是在纠正您的状况测试,但这不是问题的原因
  • 你的变量很可能是一个字符串

标签: javascript node.js vue.js webpack vuetify.js


【解决方案1】:

此代码可以检查它是否收到了预期的数据响应,然后处理该错误情况。

例如,您可以检查数据类型:

const response = await api.getAllBookmarks(this.$store.state.user.id);
const bookmarksOfThisUser = response.data;

if (Array.isArray(bookmarksOfThisUser)) {
    for(var bookmark in bookmarksOfThisUser){
        const song = (await api.getASong(bookmarksOfThisUser[bookmark]['songId'])).data;
        this.bookmarks.push(song)
    }
} else {
    // example only of logging the data that is not as expected
    console.log({response})
    console.log({bookmarksOfThisUser})
}

【讨论】:

  • 谢谢。使用你的代码我发现这是因为我的数据库不工作,所以返回的数据永远不是数组。
  • 很高兴听到它帮助您找到了核心问题!
猜你喜欢
  • 2021-02-21
  • 1970-01-01
  • 2013-02-04
  • 2016-10-11
  • 2015-09-17
  • 2021-10-06
  • 1970-01-01
  • 2022-12-07
  • 1970-01-01
相关资源
最近更新 更多