TypeError: Failed to execute 'update' on 'ServiceWorkerRegistration': Illegal invocation

TypeError: Failed to execute 'update' on 'ServiceWorkerRegistration': Illegal invocation

我有一个使用 CLI 作为 PWA 创建的 VueJS 应用程序。我的服务工作者文件如下所示:

/* eslint-disable no-console */

import { register } from 'register-service-worker'

if (process.env.NODE_ENV === 'production') {
  register(`${process.env.BASE_URL}service-worker.js`, {
    ready() {
      console.log(
        'App is being served from cache by a service worker.\n' +
          'For more details, visit https://<google-link>'
      )
    },
    registered(registration) {
      console.log('Service worker has been registered.')
      setInterval(registration.update, 1000 * 60 * 60)
    },
    cached() {
      console.log('Content has been cached for offline use.')
    },
    updatefound() {
      console.log('New content is downloading.')
    },
    updated(registration) {
      console.log('New content is available; please refresh.')
      document.dispatchEvent(new CustomEvent('swUpdated', { detail: registration }))
    },
    offline() {
      console.log('No internet connection found. App is running in offline mode.')
    },
    error(error) {
      console.error('Error during service worker registration:', error)
    }
  })
}

调用 registration.update 时,我在 setInterval 中收到 TypeError: Failed to execute 'update' on 'ServiceWorkerRegistration': Illegal invocation 错误。此间隔每小时检查一次 Web 应用程序是否有任何更新。我到处搜索,找不到导致这个问题的原因,所以我创建这个是为了帮助其他可能遇到同样问题的人。

我通过将 registration.update 包装在一个函数中解决了这个问题:

 registered(registration) {
      console.log('Service worker has been registered.')
      setInterval(() => {
        console.log('Checking for service worker update.')
        registration.update()
      }, 1000 * 60 * 60)
    },

感谢此页面帮助我解决了这个问题:https://www.kaels-kabbage.com/post/service-worker-updates/