Sullay Kaikai opened the scoring for Shrewsbury with a low strike before Cody McDonald levelled from 20 yards.
Shrewsbury regained the lead through Andy Mangan's acrobatic finish before the Gills equalised again through Jake Hessenthaler's strike from distance.
The visitors' winner came when Jean-Louis Akpa Apro's fortuitous 81st-minute deflected effort found the net.
Gillingham sixth game without a win caused them to slip out of League One's top six, leapfrogged by  Barnsley.
At the other end of the table, Shrewsbury ended their run of seven games without a win to go four points clear of the relegation zone with a game in hand.

The 22-year-old joins an impressive list at the Aegon Open on 4-12 June, including Caroline Wozniacki, Victoria Azarenka, and British top three Johanna Konta, Heather Watson and Naomi Broady.
Robson reached world number 27 in July 2013, but has struggled since returning from a serious wrist injury last year.
"I am excited to be returning to Nottingham," Robson said.
"I remember how great the grass courts are there. Preparing well on the grass is key ahead of Wimbledon and Nottingham is the perfect place to start.
"I really enjoy this time of year, to be able to play in front of a home crowd. It is fantastic to see a strong British turnout for the event as the fans always create such a great atmosphere."

The 1 mile (1.5km) park between Alum Chine and Southbourne in Bournemouth is due to open on 13 April.
The ??700,000 attraction will include a multi-sports arena, sporting events site and a dinghy park.
The work on the park will also see repairs made to a ??3.2m artificial surf reef at Boscombe, which was closed in 2011 after a boat propeller damaged it.
Local traders, hoteliers and businesses attended a series of events in January to give their feedback on the park's designs and potential benefits.
Funding for the park has been assisted by a ??254,000 grant from the government's Coastal Communities Fund.
Shrewsbury gave their survival hopes a huge boost with victory at Gillingham, who drop out of the play-off places.
[NEXT_CONCEPT]
Former British number one Laura Robson will play at next month's grass-court Wimbledon warm-up event in Nottingham.
[NEXT_CONCEPT]
Designs for a dedicated activity park along the Dorset coast have been unveiled.