Stability for dynamical systems with first integrals: a topological criterion