首页 > 解决方案 > Error of "Cannot use 'in' operator to search for '0'", which doesn't occur on localhost

问题描述

My project is on https://immense-refuge-12167.herokuapp.com/
If I login (email: a@a.com, password: 11111111, or register then login), then click the "Browser" button at the top-left corner, an error will show up in the console as shown below: TypeError: Cannot use 'in' operator to search for '0'

It only occurs on Heroku, not on localhost.

The code where the error occurred is:

      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)
            }
          }
        }
      },

I realized that it could be because bookmarksOfThisUser is of length 0, so I used if(bookmarksOfThisUser.length != 0 && !!bookmarksOfThisUser) to prevent it, but the error still occurred.
The mounted function is to populate the data bookmarks, which is an empty array by default. The element that uses this data is a v-data-table as shown below.

        <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>

I also checked its length with v-if, but the error still occurred...
Could anyone give me some hints about where I did wrong? And why it only occurs on Heroku not on localhost?

Thank you!

标签: javascriptnode.jsvue.jswebpackvuetify.js

解决方案


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

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

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})
}

推荐阅读