Apollo-client: TypeError: Object(...) is not a function in depTrackingCache.js when Upgrading from 1.2.10 to 1.3.0

Created on 10 Oct 2018  路  22Comments  路  Source: apollographql/apollo-client

Intended outcome:
Upgrading from apollo-cache-inmemory ^1.2.10 to 1.3.0
Intend no issues in consuming code
Actual outcome:
Stack trace in browser
```TypeError: Object(...) is not a function
in /node_modules/apollo-cache-inmemory/lib/depTrackingCache.js:8
this.depend = wrap(function (dataId) { return _this.data[dataId]; }, {

defaultNormalizedCacheFactory
return new DepTrackingCache(seed);
/node_modules/apollo-cache-inmemory/lib/depTrackingCache.js:60

**How to reproduce the issue:**

Consumer code  (unchanged) (originaly from React Starter Kit)
```export default function createCache() {
  // https://www.apollographql.com/docs/react/basics/caching.html#configuration
  return new InMemoryCache({
    dataIdFromObject,
  });
}

Versions

System: OS: Windows 10 Binaries: Yarn: 1.9.4 - C:\Program Files (x86)\Yarn\bin\yarn.CMD npm: 5.7.1 - C:\Program Files\nodejs\npm.CMD Browsers: Edge: 42.17134.1.0 npmPackages: apollo-cache-inmemory: 1.3.0 => 1.3.0 apollo-client: 2.4.2 => 2.4.2 apollo-link: ^1.0.7 => 1.2.1 apollo-link-error: ^1.0.3 => 1.0.7 apollo-link-http: ^1.3.2 => 1.5.3 apollo-link-logger: ^1.1.0 => 1.2.0 apollo-link-schema: ^1.0.1 => 1.0.6 react-apollo: 2.1 => 2.1.9

Most helpful comment

Stuck with this error as well, I have no idea how to fix it :(. I am using TS with next and react-apollo.

All 22 comments

Can you include more of the stack trace, including the error?

TypeError: Object(...) is not a function
new DepTrackingCache
D:/code/node_modules/apollo-cache-inmemory/lib/depTrackingCache.js:8
   5 | if (data === void 0) { data = Object.create(null); }
   6 | var _this = this;
   7 | this.data = data;
>  8 | this.depend = wrap(function (dataId) { return _this.data[dataId]; }, {
   9 |     disposable: true,
  10 |     makeCacheKey: function (dataId) {
  11 |         return dataId;
View compiled
defaultNormalizedCacheFactory
D:/code/node_modules/apollo-cache-inmemory/lib/depTrackingCache.js:60
  57 | }());
  58 | export { DepTrackingCache };
  59 | export function defaultNormalizedCacheFactory(seed) {
> 60 |     return new DepTrackingCache(seed);
  61 | }
  62 | //# sourceMappingURL=depTrackingCache.js.map
View compiled
new InMemoryCache
D:/code/node_modules/apollo-cache-inmemory/lib/inMemoryCache.js:69
  66 |     _this.config.cacheRedirects = _this.config.cacheResolvers;
  67 | }
  68 | _this.addTypename = _this.config.addTypename;
> 69 | _this.data = defaultNormalizedCacheFactory();
  70 | _this.storeReader = new StoreReader({
  71 |     addTypename: _this.config.addTypename,
  72 |     cacheKeyRoot: _this.cacheKeyRoot,
View compiled
createCache [as default]
D:/code/src/core/createApolloClient/createCache.ts:20
  17 | 
  18 | export default function createCache() {
  19 |   // https://www.apollographql.com/docs/react/basics/caching.html#configuration
> 20 |   return new InMemoryCache({
  21 |     dataIdFromObject,
  22 |   });
  23 | }
View compiled
./src/core/createApolloClient/createApolloClient.client.ts
D:/code/src/core/createApolloClient/createApolloClient.client.ts:40
  37 |   new HttpLink(resolveHttpLinkOptions()),
  38 | ]);
  39 | 
> 40 | const cache = createCache();
  41 | 
  42 | export default function createApolloClient() {
  43 |   return new ApolloClient({
View compiled
__webpack_require__
D:/code/webpack/bootstrap:763
  760 | };
  761 | 
  762 | // Execute the module function
> 763 | modules[moduleId].call(module.exports, module, module.exports, hotCreateRequire(moduleId));
  764 | 
  765 | // Flag the module as loaded
  766 | module.l = true;
View compiled
fn
D:/code/webpack/bootstrap:141
  138 |         );
  139 |         hotCurrentParents = [];
  140 |     }
> 141 |     return __webpack_require__(request);
  142 | };
  143 | var ObjectFactory = function ObjectFactory(name) {
  144 |     return {
View compiled
./src/client.js
http://localhost:3001/assets/client.js:1239:112
__webpack_require__
D:/code/webpack/bootstrap:763
  760 | };
  761 | 
  762 | // Execute the module function
> 763 | modules[moduleId].call(module.exports, module, module.exports, hotCreateRequire(moduleId));
  764 | 
  765 | // Flag the module as loaded
  766 | module.l = true;
View compiled
fn
D:/code/webpack/bootstrap:141
  138 |         );
  139 |         hotCurrentParents = [];
  140 |     }
> 141 |     return __webpack_require__(request);
  142 | };
  143 | var ObjectFactory = function ObjectFactory(name) {
  144 |     return {
View compiled
(anonymous function)
D:/code/src/clientLoader.js:1
> 1 | // polyfills
  2 | import main from './client';
  3 | 
  4 | function run() {
View compiled
./src/clientLoader.js
http://localhost:3001/assets/client.js:1545:30
__webpack_require__
D:/code/webpack/bootstrap:763
  760 | };
  761 | 
  762 | // Execute the module function
> 763 | modules[moduleId].call(module.exports, module, module.exports, hotCreateRequire(moduleId));
  764 | 
  765 | // Flag the module as loaded
  766 | module.l = true;
View compiled
fn
D:/code/webpack/bootstrap:141
  138 |         );
  139 |         hotCurrentParents = [];
  140 |     }
> 141 |     return __webpack_require__(request);
  142 | };
  143 | var ObjectFactory = function ObjectFactory(name) {
  144 |     return {
View compiled
0
http://localhost:3001/assets/client.js:2970:18
__webpack_require__
D:/code/webpack/bootstrap:763
  760 | };
  761 | 
  762 | // Execute the module function
> 763 | modules[moduleId].call(module.exports, module, module.exports, hotCreateRequire(moduleId));
  764 | 
  765 | // Flag the module as loaded
  766 | module.l = true;
View compiled
checkDeferredModules
D:/code/webpack/bootstrap:43
  40 |  }
  41 |  if(fulfilled) {
  42 |      deferredModules.splice(i--, 1);
> 43 |      result = __webpack_require__(__webpack_require__.s = deferredModule[0]);
  44 |  }
  45 | }
  46 | return result;
View compiled
(anonymous function)
D:/code/webpack/bootstrap:885
  882 | // add entry module to deferred list
  883 | deferredModules.push([0,"vendors"]);
  884 | // run deferred modules when ready
> 885 | return checkDeferredModules();
  886 | 
View compiled
(anonymous function)

So i'm debugging it and it looks like the data param to DepTrackingCache is undefined so data = Object.create(null); gets invoked. I'm not sure if this would cause the wrap function to barf, i can't step into the wrap function.. ho hum.

Hi, I've got the same issue.
I'm using "apollo-boost": "0.1.16", and I'm creating apollo client like this:

const getClient = (uri: string, headers: Headers) => new ApolloClient({
    uri,
    headers
  });

I'm building the application with webpack and I'm using babel-loader along with@babel/preset-typescript and my .tsconfig file is:

{
  "compilerOptions": {
    "target": "esnext",
    "allowJs": true,
    "checkJs": false,
    "moduleResolution": "node",
    "jsx": "react",
    "skipLibCheck": true,
    "noEmit": true,
    "lib": ["dom", "esnext"]
  },
  "files": ["./src/index.tsx"],
  "exclude": ["node_modules"]
}

I'm getting exactly the same error

@MichalPrzybylski annoying isn't it.
I was initially trying to get the upgrade to the latest version to get around this bug

However I can work around that one just by deleting the /src folder as a build step.

If you can use ^1.2.10

Please continue debugging! The error still doesn't make sense based on the information provided. You're really doing yourself a disservice if you settle for reverting to 1.2.10.

The only thing being called as a function on the line in question is the wrap function. What is the value of wrap in your debugger? What does the lib/optimism.js module look like? Does it export a function?

What browser are you using? Does the problem happen in other browsers?

If either of you could put together a small reproduction, that would be very helpful.

@damiangreen Thanks for walk around but I'd like to avoid deleting src, however I agree that this issue may be related to build process (module resolving). I'll try to provide some test-case repo on tomorrow

tl;dr

After changing my build process by removing manual compilation of TS source code stored in apollo node_modules and removing src from webpack resolve.modules - issue no longer exists

issue story

So I found the issue with my code:
Previously I set webpack resolve.modules section to

modules: ["node_modules", "src"],

I did it in order to abstract inner structure of directories with my shared components and access them as library modules.

import { QInput, QAutocomplete } from 'src/components/fileds'

but then, even though I had configured babel-loader to worki with @babel/preset-typescript, following error appeared:

ERROR in ../node_modules/apollo-cache-inmemory/src/optimism.ts 1:8
Module parse failed: Unexpected token (1:8)
You may need an appropriate loader to handle this file type.
> declare function require(id: string): any;

So I configured babel-loader to compile node_modules\/apollo.* along with the source code. In that configuration build process did not report any errors but the issue with TypeError: Object(...) is not a function in depTrackingCache.js started to appear.

solution (or rather another walk-around)

  1. Remove src from resolve.modules
  2. Remove include: [/node_modules\/apollo.*/] from babel-loader
  3. Define aliases in webpack resolve.alias like:
alias: {
      "@fields": path.resolve(__dirname, "src/components/fields")
    },

and add them to tsconfig.json paths for type checking .

This fix is not perfect as right now I need to declare each directory that should be treated as module in both webpack.config.js and tsconfig.json

Though this hardly needs to be said, Webpack gives you enough rope to tie yourself up in some pretty inscrutable knots. If you're recompiling the src directory instead of just using the lib code that we compiled, you're taking matters into your own hands, and your mileage may vary. Thanks for the thorough investigation, and I'm sorry about the time you had to sink into this!

I think @MichalPrzybylski's case may be slightly different. I've not had the capacity to do more digging but will update when i get a chance

I think @MichalPrzybylski's case may be slightly different. I've not had the capacity to do more digging but will update when i get a chance

I had this issue as well, I fixed it with:

// BEFORE (old webpack 2 code...)
modules: [
    '.',
    '..',
    path.resolve(__dirname, 'src'),
    'node_modules'
],

// AFTER (remove dot and 2-dots)
modules: [
    path.resolve(__dirname, 'src'),
    'node_modules'
],

After that, remove all node_modules and re-install (yarn install).

My full webpack:

import webpack from 'webpack'
import path from 'path'

export default function(env={}) {

  console.log(__dirname)

  const device = env.desktop
    ? 'desktop'
    : 'mobile'

  const config = {
    mode: 'development',
    devtool: 'eval'

    entry: {
      app  : `./src/${device}/index.jsx`
    },

    output: {
      path: __dirname+'/../apps/priv/static/js',
      filename: `[name].${device}.js`,
      publicPath: '/js/'
    },

    resolve: {
      modules: [
        path.resolve(__dirname, 'src'),
        'node_modules'
      ],

      extensions: env.desktop
        ? ['.webpack.js', '.desktop.js', '.desktop.jsx', '.desktop.css', '.js', '.jsx', '.css']
        : ['.webpack.js', '.mobile.js', '.mobile.jsx', '.mobile.css', '.js', '.jsx', '.css'],

      alias: {
          styles: __dirname + '/css'
        , images: __dirname + '/static/images'
      }
    },

    module: {
      rules: [
        { test: /\.(js|jsx)$/,
          exclude: /(node_modules)/,
          include: path.resolve(__dirname, 'src'),
          use: { loader: 'babel-loader' }
        },

        { test: /\.(png|jpg|gif)$/,
          include: path.resolve(__dirname, 'static'),
          use: [{loader: 'url-loader', options: {limit: 1, name: '../images/[hash].[ext]'}}]
        },

        { test: /\.svg$/,
          include: path.resolve(__dirname, 'static'),
          use: [
            {loader: 'file-loader', options: {limit: 1, name: '../images/[name].[hash].[ext]'}}
          ]
        }
      ]
    },

    plugins: [
      new webpack.DefinePlugin({
        'process.env.NODE_ENV': JSON.stringify(env.prod ? 'production' : 'development'),
      }),

      new webpack.ProvidePlugin({
        'React': 'react'
      })
    ]
  }

  if (env.prod) {
    console.log('building to production...')

    config.devtool = 'cheap-module-source-map'
    config.mode = 'production'

  }

  return config
}

Seems like I have been having the same issue as well.

Looking into the generated file webpack is unable to require the wrap function from the optimism package. (It's been frustrating cause I work on a team of 4, and it only happens to my machine)


screen shot 2018-11-29 at 2 00 36 pm

Does anyone else have the same thing occurring?

Yeah, I'm afraid i've not found time to debug it further, if you see my message above, maybe you can dig deeper.

On line 1 in the optimism.js in apollo-cache-inmemory node_modules folder I replaced this line
var wrap = require('optimism').wrap;
with
import { wrap } from 'optimism/lib'.

And now my app has started working again.

I guess this is a workaround for now, and I'm still trying to investigate why this is happening.

@benjamn does @markfranco's suggestion make sense? Is this something we could do on the main br anch?

I got stuck with the same error at the same line:

this.depend = Object(_optimism__WEBPACK_IMPORTED_MODULE_0__["wrap"])(function (dataId) { return _this.data[dataId]; }, {

I wonder though why the issue was closed. Are new users expected to apply the (rather obscure looking) work-around? I'm looking forward to switch to graphql later (it seems an impressive piece of work), but for the moment I will stick to my REST api.

EDIT: reverting to 1.2.10 does seem to work, so I will continue from there
EDIT2: hmm, no, with 1.2.10 I still get the same error

I agree this issue really needs reopening

Stuck with this error as well, I have no idea how to fix it :(. I am using TS with next and react-apollo.

@markfranco @benjamn did you make headway with this?

@damiangreen , have you found the solution yet ?

No.. afraid not. I was hoping @benjamn would fix this. I'm still waiting on upgrading until it gets fixed

Mysteriously this issue disappeared when we upgraded all Apollo libraries (as opposed to upgrading this single library.

In case it helps others we upgraded to:

"apollo-cache-inmemory": "^1.5.1",
"apollo-client": "2.5.1",
"apollo-link": "^1.2.11",
"apollo-link-batch-http": "^1.2.11",
"apollo-link-error": "^1.1.10",
"apollo-link-http": "^1.5.14",
"apollo-link-logger": "^1.2.3",
"apollo-link-schema": "^1.2.2",
Was this page helpful?
0 / 5 - 0 ratings